我想在Number原型(prototype)函数中覆盖this,动态改变变量的值,例如:
Number.prototype.xd = function(){
this = 11212;
}
var a = 171717;
console.log(a);
a.xd();
console.log(a);
是我想要的,但它会引发错误。 Array.prototype.pop 方法以这种方式工作:
fruits = ["a","b","c","d"];
console.log(fruits);
fruits.pop();
console.log(fruits);
我可以这样做吗?
最佳答案
你无法实现你想要的,因为 JS 中的数字是不可变的。
这不起作用的另一个原因是因为 this
根据其定义在 JS 中已经是动态的,因此每次调用函数时它都会自动更改,具体取决于它的调用方式。
关于javascript - JS - 在原型(prototype)函数中覆盖它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41553066/