What will be the output of the following code?
What will be the output of the following code?
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();
The output of the above code will be:
outer func: this.foo = bar
outer func: self.foo = bar
inner func: this.foo = undefined
inner func: self.foo = bar
Here's the explanation for the output:
outer func: this.foo = bar
- In the context of myObject.func()
, this
refers to myObject
. Therefore, this.foo
is equivalent to myObject.foo
, which is "bar"
.
outer func: self.foo = bar
- The variable self
is assigned the value of this
in the context of myObject.func()
. Since self
and this
are the same in this context, self.foo
is also "bar"
.
inner func: this.foo = undefined
- The inner function is an immediately invoked function expression (IIFE) that has its own this
context. In a browser, if the IIFE is not bound to any context, this
would refer to the global object (window
in a browser), which does not have a foo
property, hence undefined
. If the code is running in strict mode, this
would be undefined
, and attempting to access this.foo
would throw an error.
inner func: self.foo = bar
- The variable self
is still accessible within the IIFE, and it refers to the myObject
context as captured outside of the IIF...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào