字符串原型修改自身

时间:2009-10-23 18:46:27

标签: javascript string prototype

据我所知,不可能以这种方式修改对象:

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

因此,根本不可能让字符串函数自行修改吗?

4 个答案:

答案 0 :(得分:17)

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

答案 1 :(得分:3)

虽然字符串是不可变的,但尝试在任何类中将任何分配给this都会引发错误。

答案 2 :(得分:0)

我一直在研究相同的...首先,当然你不能只做+ = 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());

这很烦人,但你去了

答案 3 :(得分:-2)

字符串是不可变的;你问的是说:“为什么我不能这样做:

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

...?“