Updating object value from prototype function

后端 未结 4 343
余生分开走
余生分开走 2020-12-20 01:32

I\'m trying to do this:

String.prototype.clear = function(){
    alert(this.value);
    this = \'\'; // I want to set value to \'\' here
}

var temp = \'Hell         


        
相关标签:
4条回答
  • 2020-12-20 02:14

    To make it short:

    You can't.

    Strings are immutable. Once it is made, a string can never be changed.

    You have to set your string to an empty string to "clear" it

    var str = "String";
    str='';
    

    Note that this won't change the string but sets str to a new Instance of a String, the old one gets garbage collected

    It is even shorter then calling a Prototypes method of the Object which would do exactly the same. And you don't have to temper with the native Objects prototypes


    Edit - Thx for pointing that out Florian Margaine

    If you have many occurences of setting empty Strings and might change your future "definition" of clearing, you could either use a funciton that returns `` or a empty String

    function clearString () {
        return ''
    }
    var str = "Asd"
    var str = clearString()
    

    Or simply Set a variable to an empty String

    var emptyString = ''
    var str = "Asd"
    str = emptyString //''
    

    Now if you want to change '' into null or undefined

    var emptyString = null

    Which would work as well, since primitive data types are being passed as value and not by reference

    But i would suggest not modifying an Objects prototype for something like this

    0 讨论(0)
  • 2020-12-20 02:15

    You can create a class called MyMutableString like:

    function MyMutableString(s) {
       this.string = s;
       this.clear = function() {
          this.string = "";
       }
    }
    

    Now you create an instance and use it like like:

    var s = new MyMutableString("my str");
    s.clear(); // makes string stored inside object `s` empty
    console.log(s.string);
    
    0 讨论(0)
  • 2020-12-20 02:19

    Aside from creating a wrapper, the best way is to just go with the functional way.

    String.prototype.clear = function() {
        return '';
    };
    
    var t = 'hello';
    t = t.clear();
    

    Why not just doing t = '';, you say? Well, clearing today might mean putting '', but it might mean putting null tommorrow. Having a single point to change it might be worth it. Or not at all.

    0 讨论(0)
  • 2020-12-20 02:22

    what about a object copy like this?

    String.prototype.clear = function(){
        alert(this);
        return '';
    }
    
    
    var temp = 'Hello';
    var newTemp = temp.clear();
    alert(newTemp);
    
    0 讨论(0)
提交回复
热议问题