我是 JavaScript 中“类”的新手,所以我希望我在问题中使用了正确的术语。
我认为构造函数中的 this.Variables 可以通过原型(prototype)定义的所有函数使用。 这在一个方向上似乎是正确的,但我无法从函数内更新变量。
这是一个小jsfiddle https://jsfiddle.net/2g4vnL9b/
var littleTest = function() {
this.testVar = "blub";
}
littleTest.prototype = {
changeTestVar: function(val) {
this.testVar = val;
},
changeTestVar2: function(val) {
return val;
}
}
var myTest = new littleTest();
console.log(myTest.testVar); // -> blub
myTest.changeTestVar = "foo";
console.log(myTest.testVar); // -> blub
myTest.testVar = myTest.changeTestVar2("foo");
console.log(myTest.testVar); // -> foo
我正在尝试从函数 test.changeTestVar 更新 this.testVar,但它没有保存在对象内以供以后使用。只有当我直接设置它时才会保存。 有人可以解释一下为什么我的代码的行为如此以及我必须更改什么吗?
非常感谢
最佳答案
您需要将 changeTestVar
作为函数调用,而不是用新值覆盖它。
尝试以下操作:
myTest.changeTestVar("foo");
console.log(myTest.testVar);
此外,changeTestVar2
根本不会更改 this
变量,它只是返回传入的值。这通常称为“身份”函数,但它并没有“不会对您的对象产生任何持久影响。
关于JavaScript:在构造函数中使用原型(prototype)函数更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35273089/