javascript - Assigning method to variable and problems with this -
i have piece of code:
function a(){ this.count = 0; } a.prototype.inc = function(){ this.count++; } var = new a(); a.inc(); var f = a.inc; f();
the last line deosn't work expected, because this
object of type window
. something, shouldn't - assign methods variables, in case make use of this
?
when want use method argument, should omit fn(a.inc)
, use regular function, , use insted following?
fn(function(){ a.inc(); });
this famous "lost binding" of javascript.
you have do:
f = a.inc.bind(a);
because if say
f = a.inc; f();
then when f
running, this
not bound a
. bound global object, window
.
the rule is, if a.fn()
, inside of function, this
bound a
, if fn()
or g()
, when g === a.fn
, inside of function, this
bound global object, window
.
to bind this
explicitly a
when function invoked, have use a.inc.bind(a)
if don't want use bind
want use own function, that's fine too. do:
function fn() { a.inc(); }
or form:
var fn = function() { a.inc(); };
this way, fn
closure captures context, , able use a
, in scope in scope chain.
Comments
Post a Comment