1

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 

2 Answers 2

1

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().

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.