Value unchanged when another function is called in javascript -
i reading article. related javascript. here, code sample article. please @ 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 why value "o.value" unchanged when changer(o.inc) called ?
o.inc reference anonymous function:
function() { this.value++; } whereas this scope in function executed. when run changer(o.inc), this pointing global, in browsers it's window. doesn't have o.
you bind scope 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));
Comments
Post a Comment