String prototype modifying itself

后端 未结 4 2025
广开言路
广开言路 2021-02-20 16:09

As far as i know it\'s not possible to modify an object from itself this way:

String.prototype.append = function(val){
    this = this + val;
}

相关标签:
4条回答
  • 2021-02-20 16:53

    While strings are immutable, trying to assign anything to this in any class will throw an error.

    0 讨论(0)
  • 2021-02-20 17:01

    I've been researching the same... First of all, of course you can't just do this += x, 'this' is an object, you can't use the + operator on objects.

    There are 'behind the scene' methods that get called - for example

    String.prototype.example = function(){ alert( this ); }
    

    is actually calling

    String.prototype.example = function(){ alert( this.valueOf() ); }
    

    So what you need to find is a relevant value that does the the opposite - something like this.setValue(). Except that there isn't one. The same holds for Number too.

    Even the built in methods are bound by that

    var str = 'aaa';
    str.replace( /a/, 'b' );
    console.log( str ); // still 'aaa' - replace acts as static function 
    str = str.replace( /a/, 'b' );
    console.log( str ); // 'bbb' - assign result of method back to the object
    

    On some other objects you can; for example on a Date:

    Date.prototype.example = function(){
     this.setMonth( this.getMonth()+6 );
    };
    var a=new Date();
    alert(a.getMonth());
    a.example();
    alert(a.getMonth());
    

    It's annoying, but there you go

    0 讨论(0)
  • 2021-02-20 17:05

    The String primitives are immutable, they cannot be changed after they are created.

    Which means that the characters within them may not be changed and any operations on strings actually create new strings.

    Perhaps you want to implement sort of a string builder?

    function StringBuilder () {
      var values = [];
    
      return {
        append: function (value) {
          values.push(value);
        },
        toString: function () {
          return values.join('');
        }
      };
    }
    
    var sb1 = new StringBuilder();
    
    sb1.append('foo');
    sb1.append('bar');
    console.log(sb1.toString()); // foobar
    
    0 讨论(0)
  • 2021-02-20 17:13

    Strings are immutable; what you're asking is like saying, "Why can't I do:

    Number.prototype.accumulate = function (x) {
        this = this + x;
    };
    

    ...?"

    0 讨论(0)
提交回复
热议问题