1

I was reading an article. It is related to javascript. Here, is a code sample from the article. Please look at below.

function customobject(){ 
this.value = 2; 
} 

customobject.prototype.inc = function(){ 
this.value++;
 } 

function changer(func){ 
func();
 } 

var o = new customobject();
 
alert(o.value);   
o.inc(); 
alert(o.value);  
changer(o.inc); 
alert(o.value); 

My question is Why is the value for "o.value" unchanged when changer(o.inc) is called ?

1
  • 4
    you should log the value of this and you will see what happens. the problem is that you call inc without the this context. If you want to make it work you have to do changer(o.inc.bind(o)) . bind doc Commented Sep 30, 2015 at 12:56

2 Answers 2

3

o.inc is just a reference to the anonymous function:

function() { 
    this.value++;
}

Whereas this is the scope in which the function is executed. So when you run changer(o.inc), this is actually pointing to the global, in browsers it's window. It doesn't necessarily have anything to do with o.

You could bind the scope like this:

function changer(func, scope){ 
    func.call(scope); // or apply
} 

changer(o.inc, o); 

Or simply:

function changer(func){ 
    func();
}
changer(o.inc.bind(o));
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is because Function does not save instance for objects. You have to pass the object as argument so call your function, like this.

function customobject(){ 
    this.value = 2; 
} 

customobject.prototype.inc = function(){
    this.value++;
} 

function changer(o){ 
   o.inc();
} 

var o = new customobject();
 
console.log(o.value);  //It has to print 2 
o.inc();               //Increment to 3
console.log(o.value);  //It has to print 3
changer(o);            //Increment to 4
console.log(o.value);  //It has to print 4

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.