celevra February 2016

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.

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

Answers


adeneo February 2016

ChangeTestVar is a function, and it's written in different case

var myTest = new littleTest();
console.log(myTest.testVar); // -> blub

myTest.changeTestVar("foo");
console.log(myTest.testVar); // -> foo

FIDDLE


TbWill4321 February 2016

You need to call changeTestVar as a function, not overwrite it with a new value.

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.


santi6291 February 2016

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


Paco q February 2016

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); 

Post Status

Asked in February 2016
Viewed 3,830 times
Voted 9
Answered 4 times

Search




Leave an answer