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