英文:
Unable to assign to the value of `this` for a string prototype definition
问题
无法为字符串原型定义分配给 this
值。
function testfunction(thisValue) {
thisValue = thisValue || this;
thisValue = "new test";
console.log(thisValue);
this = thisValue; // 这会引发错误
}
Object.defineProperty(String.prototype, 'testfunction', { value: testfunction, enumerable: true });
let s = "i am a test";
s.testfunction()
对于 Array
对象,我正在使用 this.push
。对于 String
分配一个新值是什么意思。
英文:
Unable to assign to the value of this
for a string prototype definition.
function testfunction(thisValue) {
thisValue = thisValue || this;
thisValue = "new test";
console.log(thisValue);
this = thisValue; // this throws error
}
Object.defineProperty(String.prototype, 'testfunction', { value: testfunction, enumerable: true });
let s = "i am a test"
s.testfunction()
for Array
object I am using this.push
. What is it for String
to assign a new value.
答案1
得分: 1
以下是翻译好的部分:
"可以将方法添加到String原型中,这是完全可能的。有些人认为这很糟糕,但我觉得如果你小心并且了解一般情况和你特定领域的影响,那就还好。我不是你的父亲,所以你可以按照自己的意愿行事。
但是,我 不会 使这些方法可枚举,因为这是修改标准原型的最大问题之一。另外,对于像String、Number和Boolean这样的东西,你不能修改底层的原始值,因为它们是不可变的。当你在字符串原始值上调用方法时,实际上是为了评估表达式而实例化了一个包装对象,然后将该对象丢弃。因此,可以从基本原始字符串(或数字或布尔值)计算某个值的方法可以执行有趣的操作,但你不能修改这些值。"
英文:
It's certainly possible to add methods to the String prototype. Some people think that's terrible, but my feeling is that if you're careful and you understand the implications in general and for your specific universe, then it's not so bad. I'm not your dad so do what you want.
That said, I would not make such methods enumerable, because that's one of the biggest problems with modifying standard prototypes. Also, for things like String, Number, and Boolean, you cannot modify the underlying primitive values because they're not mutable. When you invoke a method on a string primitive value, what's happening is that a wrapper object is instantiated for the purpose of evaluating the expression, and then that object is thrown away. Thus methods that compute some value from the base primitive string (or number or boolean) can do interesting things, but you can't modify those values.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论