Help us understand the problem. What is going on with this article?

メソッドの定義とthisを整理

More than 1 year has passed since last update.
  • 関数宣言
  • アロー関数式
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
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away