有没有办法给变量(数字)添加原型,原型可以改变变量本身? [英] Is there a way to add a prototype to variables (numbers), and the prototype can change the variable itself?
问题描述
我知道将原型添加到原生 javascript 对象是一个坏主意,但我想将原型添加到一个变量中,例如 Number.limit(min, max);
其中变量可以通过原型改变.
I know its a bad idea to add prototypes to native javascript objects, but I'd like to add a prototype to a variable such as Number.limit(min, max);
where the variable can be changed by the prototype.
Number.prototype.limit = function(min, max) {
if (this < min) {
this = min;
} else if (this > max) {
this = max;
}
};
似乎使用 this
在赋值错误中给出了无效的左侧
it appears that using this
gives a Invalid left-hand side in assignment error
我已经搜索过谷歌和堆栈溢出,但没有回答我的问题
I have searched through google and stack overflow and nothing has answered my question
所以有可能吗?我该怎么做?
so is it even possible? and how would I do it?
推荐答案
不,这是不可能的(在大多数情况下) - 你能做的最好的事情就是返回新的调用者重新分配的值:
No, it's not possible (for the most part) - the best you'll be able to do is to return the new value, which the caller reassigns:
Number.prototype.limit = function(min, max) {
if (this < min) {
return min;
} else if (this > max) {
return max;
}
return this;
};
let num = 5;
let newNum = num.limit(10, 15);
console.log(newNum);
如果您熟悉 Javascript,要了解 为什么这是不可能的,那么查看没有实现的方法的调用可能会有所帮助:
If you're familiar with Javascript, to understand why it's not possible, it might help to look at the invocation of a method without the implementation:
let someVar = <something>;
someMethod(someVar);
无论someMethod
做什么,someVar
变量名在上述范围内绑定的对象或原语都不能被someMethod
(除非 someMethod
也在该范围内定义,这是一个位奇怪的并且通常不是这种情况).除非 someMethod
也有 someVar
的词法范围并且执行 someVar = <somethingElse>
,someVar
将保持引用<代码><某事>代码>.尽管 someMethod
可以改变
,但如果它是一个对象,它不能重新分配someVar
另一个作用域中的变量名.
No matter what someMethod
does, the object or primitive that the someVar
variable name is bound to in the scope above is not changeable by someMethod
(unless someMethod
is also defined in that scope, which is a bit weird and is often not the case). Unless someMethod
also has lexical scope of someVar
and does someVar = <somethingElse>
, the someVar
will remain referencing <something>
. Although someMethod
may mutate the <something>
, if it's an object, it cannot reassign the someVar
variable name in the other scope.
这篇关于有没有办法给变量(数字)添加原型,原型可以改变变量本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!