[英]JavaScript: change a variable with a prototype function inside the constructor
我是JavaScript中“類”的新手,所以我希望我在問題中使用了正確的術語。
我對此很堅信,構造函數中的變量可以通過原型定義的所有函數使用。 這似乎在一個方向上是正確的,但是我無法從函數中更新變量。
這是一個小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
變量,它只返回傳入的值。通常稱為“身份”函數,但對對象沒有任何持久性影響。
ChangeTestVar
是一個函數,它用不同的大小寫
var myTest = new littleTest();
console.log(myTest.testVar); // -> blub
myTest.changeTestVar("foo");
console.log(myTest.testVar); // -> foo
您的代碼無法使用的原因是因為您覆蓋了原型函數
myTest.changeTestVar = "foo"; //this is replacing the function for a string
console.log(myTest.testVar); // -> blub
由於您調用函數時,應像其他功能一樣傳遞值
myTest.changeTestVar("foo");
console.log(myTest.testVar); // -> foo
您在將參數傳遞給函數時錯了,因為您可以直接更改變量
var myTest = new littleTest();
console.log(myTest.testVar);
myTest.testVar="foo";
console.log(myTest.testVar);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.