javascript - why this is ref to window Obj here? -
javascript - why this is ref to window Obj here? -
i new js , felt understood concept of this until came across.
function toplevelfn(){ var obj = { empid : 232 }; console.log('toplevelfn() empid :' + obj.empid); innerfn(); function innerfn(){ //why points window object... console.log('innerfn() empid :' + this.obj.empid); } } var register = new toplevelfn();
if understood innerfn() called toplevelfn() invoking obj , this should ref toplevelfn()?
context depends on how invoke function. case described in ecmascript spec 10.4.3 entering function code:
the next steps performed when command enters execution context function code contained in function object f, caller provided thisarg, , caller provided argumentslist:
if function code strict code, set thisbinding thisarg. else if thisarg null or undefined, set thisbinding global object.since don't provide thisarg
function executed in global context.
now may inquire how provide thisarg
value? ecmascript defines 3 methods explicitly specify execution context: function.prototype.call
, function.prototype.apply
, function.prototype.bind
(returns new function). in case can utilize call
this:
innerfn.call(this);
in case innerfn
invoked in context of this
object. otherwise innerfn()
have global context.
javascript
Comments
Post a Comment