javascript - Why we cannot access the 'this' inside the inner function? -
this question has answer here:
- iife invocation in javascript 1 answer
- how “this” keyword work? 18 answers
in code below, there 2 functions, outer function, , inner iife function.
the output code below is:
outer func: this.foo = bar outer func: self.foo = bar inner func: this.foo = undefined inner func: self.foo = bar
i not understand why in inner iife function, this
cannot used access foo variable while self
still can. understand var self
global varible inner function , can still accessed. this
?
var myobject = { foo: "bar", func: function() { var self = this; console.log("outer func: this.foo = " + this.foo); console.log("outer func: self.foo = " + self.foo); (function() { console.log("inner func: this.foo = " + this.foo); console.log("inner func: self.foo = " + self.foo); }()); } }; myobject.func();
in inner function, this
can referenced, has different value in outer function. every function call involves setting this
particular call inside called function. note it's every function call determines this
; it's not inherent nature of function, it's how function called.
in case, anonymous inner function called without explicit value this
, value reference global object (window
in browser). in "strict" mode, value undefined
.
you force this
self
:
(function() { console.log("inner func: this.foo = " + this.foo); console.log("inner func: self.foo = " + self.foo); }.call(self));
by using .call()
, explicit value this
inside anonymous function assures reference same object.
Comments
Post a Comment