String prototype modifying itself

后端 未结 4 2096
广开言路
广开言路 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 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

提交回复
热议问题