[英]JavaScript: change a variable with a prototype function inside the constructor
i'm new to "classes" in JavaScript so i hope i've used the right terms in my question. 我是JavaScript中“类”的新手,所以我希望我在问题中使用了正确的术语。
I tought the this.Variables in the Constructor could be used through all the functions defined with prototype. 我对此很坚信,构造函数中的变量可以通过原型定义的所有函数使用。 This seems right in one direction but i'm not able to update the variable from within a function.
这似乎在一个方向上是正确的,但是我无法从函数中更新变量。
Here is a little jsfiddle https://jsfiddle.net/2g4vnL9b/ 这是一个小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
i'm trying to update the this.testVar from the function test.changeTestVar, but it isn't saved inside the object for later use. 我正在尝试从功能test.changeTestVar更新this.testVar,但未将其保存在对象中以备后用。 Only if i set it directly it is saved.
仅当我直接设置它时,它才能保存。 Can somebody explain me why my code behaves like it behaves and what i have to change?
有人可以解释我为什么我的代码表现得像我一样,以及我必须更改什么吗?
thank you very much 非常感谢你
You need to call changeTestVar
as a function, not overwrite it with a new value. 您需要将
changeTestVar
作为函数调用,而不是用新值覆盖它。
Try the following: 请尝试以下操作:
myTest.changeTestVar("foo");
console.log(myTest.testVar);
Also, changeTestVar2
doesn't change this
variables at all, it just returns the value passed in. That's normally called an "identity" function, but it doesn't have any persisting effect on your object. 另外,
changeTestVar2
根本不更改this
变量,它只返回传入的值。通常称为“身份”函数,但对对象没有任何持久性影响。
The reason you code won't work is because your overwriting your prototype functions 您的代码无法使用的原因是因为您覆盖了原型函数
myTest.changeTestVar = "foo"; //this is replacing the function for a string
console.log(myTest.testVar); // -> blub
since your calling a function the value should be passed like any other fucntion 由于您调用函数时,应像其他功能一样传递值
myTest.changeTestVar("foo");
console.log(myTest.testVar); // -> foo
you were wrong when passing the parameter to the function, by the way you can change the variable directly 您在将参数传递给函数时错了,因为您可以直接更改变量
var myTest = new littleTest();
console.log(myTest.testVar);
myTest.testVar="foo";
console.log(myTest.testVar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.