Issue with Javascript this context -
this question has answer here:
i'm having issue following code.console.log
working fine in logname
method not giving desired output in lognameagain
method. tried google in vain. please explain going on here?
var testobj = { name: "this test object", logname: function() { console.log(this.name); //works fine function lognameagain() { console.log(this.name); //not giving expected result; } lognameagain(); } }; testobj.logname();
seems console.log
in lognameagain
method pointing window
. doesn't make sense me?
update: understand can fixed using bind/call or self don't understand why happening?
try using .bind()
(see working jsfiddle):
var testobj = { name: "this test object", logname: function() { console.log(this.name); var lognameagain = function() { console.log(this.name); }.bind(this); lognameagain(); } }; testobj.logname();
the problem new function inside of logname
has window
(global) context. means need somehow pass in local context. function.prototype.bind
that.
if browser support concern, can hacky thing:
var testobj = { name: "this test object", logname: function() { var = this; console.log(this.name); var lognameagain = function() { console.log(that.name); }; lognameagain(); } }; testobj.logname();
that's if need support ie8 , below. here's compat table .bind()
(courtesy of mdn:
Comments
Post a Comment