字符串原型修改自身 [英] String prototype modifying itself

查看:42
本文介绍了字符串原型修改自身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

String 原语是不可变的,它们在创建后不能改变.

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

这篇关于字符串原型修改自身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆