LoginSignup
1
1

More than 3 years have passed since last update.

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

Posted at
  • 関数宣言
  • アロー関数式
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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1