从原型函数更新对象值 [英] Updating object value from prototype function
问题描述
我正在尝试这样做:
String.prototype.clear = function(){
alert(this.value);
this = ''; // I want to set value to '' here
}
var temp = 'Hello';
temp.clear();// After this step temp should be ''
但是我收到了无效的左手分配错误。我发现这个问题作为参考,但它并不是我想要的。
我也发现'this'是不可变的。
But I'm getting invalid left hand assignment error. and I found this question as reference, but it's not really what I want. I also find out that 'this' is Immutable.
那么,有什么方法可以完成我的任务吗?我不是在任何地方使用它。只是在玩耍。
谢谢。
So, is there any way to do my task? I'm not using it any where. Just playing around. Thanks.
推荐答案
缩短期限:
你不能。
字符串是不可变的。一旦创建,就永远不能更改字符串。
Strings are immutable. Once it is made, a string can never be changed.
您必须将字符串设置为空字符串以清除它
You have to set your string to an empty string to "clear" it
var str = "String";
str='';
请注意,这不会更改字符串,但会设置 str
到一个新的String实例,旧的实例收集垃圾
Note that this won't change the string but sets str
to a new Instance of a String, the old one gets garbage collected
它比调用Prototypes方法更短对象将完全相同。 和你不必使用原生对象原型进行调整
It is even shorter then calling a Prototypes method of the Object which would do exactly the same. And you don't have to temper with the native Objects prototypes
编辑 - Thx for指出 Florian Margaine
Edit - Thx for pointing that out Florian Margaine
如果你有很多事情发生设置空字符串并可能改变你未来的清算定义,你可以使用一个返回``或空字符串的函数
If you have many occurences of setting empty Strings and might change your future "definition" of clearing, you could either use a funciton that returns `` or a empty String
function clearString () {
return ''
}
var str = "Asd"
var str = clearString()
或者只是将变量设置为空字符串
Or simply Set a variable to an empty String
var emptyString = ''
var str = "Asd"
str = emptyString //''
现在,如果您想将''
更改为 null
或 undefined
Now if you want to change ''
into null
or undefined
var emptyString = null
哪个也可以,因为原始数据类型被传递为值而非参考
Which would work as well, since primitive data types are being passed as value and not by reference
但我建议不要修改像这样的对象原型
But i would suggest not modifying an Objects prototype for something like this
这篇关于从原型函数更新对象值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!