[Javascript] this: What get logged?

发布时间 2023-06-26 02:11:24作者: Zhentiw

 

 

What this refer to?

function regularFunction() {
  this // Global scope
}

const obj = {
  regularFunction() {
    this // The object on which the method is called
  }
}

 

const objA = {
  type: "A",
  foo() {
    console.log(this.type) // objA  
  }
}

const objB = {
  type: "B",
  foo: objA.foo, // this refers to objB
  bar: () => {
    this // Global scope
    objA.foo()
  },
  baz() { 
    this // objB
    objA.foo()
  }
}

 

objB.foo() which is foo: objA.foo, equals to foo: () { console.log(this.type)}, logs B

objB.bar() it is a arrow function, this is global scioe, caller is objA, so it logs A

obj.baz() it is a regular function, this is objB, but caller is still objA, so it logs A