i'm new to "classes" in JavaScript so i hope i've used the right terms in my question.
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/
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. 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
myTest.changeTestVar = "foo";Probably you meanmyTest.changeTestVar("foo");?changeTestVar2you are not settingthis.testVar2you are just returning what is passed inthis.testVarin the method creates an own property to the instance called the method.testVarin the prototype keeps its value, and when you create new instances oflittleTest,testVarin those instances will be"blub".