1

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?

Ezio_
  • 593
  • 3
  • 9
  • 23
  • That `prop` becomes a representation of the variable in the context of the function. It's not actually set to `this.x`, you're just passing the value of `this.x` by reference. Primitives are passed by value, while Objects are passed by "copy of a reference". This is a possible [duplicate](https://stackoverflow.com/questions/13104494/does-javascript-pass-by-reference). –  Jan 26 '16 at 20:43

1 Answers1

1

When passing in a primitive type, like a number/string, the value is passed in by value, but when you're passing in an object/array/function, it is by reference. You were passing in the object's property, not the object itself.

var myClass = (function(){
    function myClass(){
         this.x = 5;
    }

    myClass.prototype.changeX = function(prop, val){
         prop.x = val;
    }

    myClass.prototype.changer = function(){
         this.changeX(this, 10); //Pass the object, not the object property
    }

    return myClass;
})();

var myObj = new myClass();
console.log(myObj);    //myClass {x: 5}

myObj.changer();
console.log(myObj);    //myClass {x: 10}

By value:

  • null
  • undefined
  • string
  • number
  • boolean

By reference:

  • object
  • array
  • function
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98