首页 > 解决方案 > 如何从 String.prototype 更改 String 的值?

问题描述

我写了这段代码:

String.prototype.toJadenCase = function () {
  return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ')
}

let text = 'hello world'
text.toJadenCase()
alert(text) // hello world

它不会改变字符串的值,从调用的函数是。正如我在这里看到的:String prototype changed the string value,它应该可以工作,但它没有

感谢所有的帮助!

标签: javascriptnode.jsstring

解决方案


不能更改字符串的值,字符串是不可变的。您所能做的就是创建一个字符串并返回它:

    text = text.toJadenCase()
//  ^^^^^^^

String.prototype.toJadenCase = function () {
  return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ')
}

let text = 'hello world'
text = text.toJadenCase()
alert(text) // hello world


旁注:它不如String.prototype其他一些重要,但最佳实践是将添加到内置原型中的任何内容(如果您向其中添加任何内容)定义为non-enumerable,这是您使用时的默认设置Object.defineProperty

Object.defineProperty(String.prototype, "toJadenCase", {
    value: function () {
        return this.split(/\s/).map(word => word[0].toUpperCase() + word.substr(1)).join(' ');
    },
    writable: true,
    configurable: true
});

推荐阅读