this.message = 'global';
// function statement
function func_st() { console.log(`this is ${this.message}`) }
const obj_st1 = {
message: 'local',
func: func_st,
}
const obj_st2 = {
message: 'local',
func: function () { console.log(`this is ${this.message}`) },
}
const obj_st3 = {
message: 'local',
func() { console.log(`this is ${this.message}`) },
}
// arrow function expression
const func_ex = () => { console.log(`this is ${this.message}`) }
const obj_ex1 = {
message: 'local',
func: func_ex,
}
const obj_ex2 = {
message: 'local',
func: () => { console.log(`this is ${this.message}`) },
}
obj_st1.func(); // -> this is local
obj_st2.func(); // -> this is local
obj_st3.func(); // -> this is local
obj_ex1.func(); // -> this is global
obj_ex2.func(); // -> this is global