What I know so far for JavaScript is that parameters passed to a function are passed by value, but the values itself are references. Let's look at the following example:
function change(obj){
obj.x = 10;
}
var myObj = {x: 5};
console.log(myObj); //Object {x: 5}
change(myObj);
console.log(myObj); //Object {x: 10}
Let's say we have the following class:
var myClass = (function(){
function myClass(){
this.x = 5;
}
myClass.prototype.changeX = function(val){
this.x = val;
}
return myClass;
})();
var myObj = new myClass();
console.log(myObj); //myClass {x: 5}
myObj.changeX(10);
console.log(myObj); //myClass {x: 10}
Everything looks okay so far. And let's extend our class:
var myClass = (function(){
function myClass(){
this.x = 5;
}
myClass.prototype.changeX = function(prop, val){
prop = val;
}
myClass.prototype.changer = function(){
this.changeX(this.x, 10);
}
return myClass;
})();
var myObj = new myClass();
console.log(myObj); //myClass {x: 5}
myObj.changer();
console.log(myObj); //myClass {x: 5}
So why in the latest example the myObj
's x
property is not changed? How can I modify the latest example's changer
method so that it calls changeX
method by sending this.x
and value to be assigned to it as a parameter?