Câu hỏi phỏng vấn Javascript
Câu hỏi

What will be the output of the following code?

Câu trả lời

javascript Copy
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:

Copy
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:

  1. 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".

  2. 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".

  3. 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.

  4. 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

middle

Gợi ý câu hỏi phỏng vấn

junior

What's the difference between throw Error('msg') vs throw new Error('msg') ?

middle

What is the motivation for bringing Symbol to ES6?

middle

What is IIFEs (Immediately Invoked Function Expressions)?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào