最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - String prototype modifying itself - Stack Overflow

programmeradmin1浏览0评论

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;
}

So is it not possible at all to let a string function modify itself?

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;
}

So is it not possible at all to let a string function modify itself?

Share Improve this question asked Oct 23, 2009 at 18:46 ChrisRChrisR 14.4k17 gold badges72 silver badges110 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 19

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

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

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

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

...?"

发布评论

评论列表(0)

  1. 暂无评论