代码之家  ›  专栏  ›  技术社区  ›  ChrisR

字符串原型修改自身

  •  9
  • ChrisR  · 技术社区  · 15 年前

    据我所知,不可能这样修改对象本身:

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

    那么,是否根本不可能让一个字符串函数修改它自己呢?

    4 回复  |  直到 12 年前
        1
  •  17
  •   I159    12 年前

    这个 String 原语是不可变的,创建后不能更改。

    这意味着其中的字符可能不会被更改,对字符串的任何操作实际上都会创建新的字符串。

    也许您想实现某种字符串生成器?

    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
    
        2
  •  3
  •   Matt Baker    15 年前

    当字符串不可变时,尝试分配 任何东西 this 在里面 任何 类将引发错误。

        3
  •  0
  •   gotofritz    15 年前

    我也在研究这个…首先,当然你不能只做+=x,'这'是一个对象,你不能在对象上使用+操作符。

    有一些“幕后”方法被调用-例如

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

    正在打电话

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

    因此,您需要找到一个与之相反的相关值-类似于this.setValue()。只是没有。数字也是如此。

    即使是内置的方法也受此约束

    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
    

    在某些其他对象上,您可以;例如在某个日期上:

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

    很烦人,不过你去吧

        4
  •  -2
  •   Anthony Mills    15 年前

    字符串是不可变的;您所要求的就像是说,“为什么我不能:

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

    …?“