Tarek Saied
Tarek Saied

Reputation: 6626

Passing by Reference in JavaScript(Call Method)

my problem here that i don't understand how does the method called "objectchanger" works here is the source

function test()
{
  this.value=5;
}

test.prototype.Add=function()
{
  this.value++;
};

var obj = new test();

obj.Add();

alert(obj.value);


function objectchanger(fnc, obj)
{
  fnc.call(obj); 
  //obj.fnc(); >> without this line of code it works fine but why?????
  //why i don't need to write this code --
}

objectchanger(obj.Add, obj);
alert(obj.value); // the value is now 7 

Upvotes: 1

Views: 216

Answers (2)

Scorpion-Prince
Scorpion-Prince

Reputation: 3634

When the "this" object is accessed within a javascript function, it takes it from the current executing context. By passing the "obj" in the call method, the "this" object within the function is set to the passed in object.

Upvotes: 0

Jamison Dance
Jamison Dance

Reputation: 20184

call is a method on the Function object. It calls a function with the passed-in object as the this value in the function. See the MDN docs on call.

So when objectchanger calls fnc.call(obj), it is calling test.prototype.Add.call(obj), which is the same as calling obj.Add().

Upvotes: 1

Related Questions