関数とメソッドにおけるthis
関数の種類
code:func.js
// functionキーワードからはじめる関数宣言
function fn1() {}
// functionを式として扱う関数式
const fn2 = function() {};
// Arrow Functionを使った関数式
const fn3 = () => {};
メソッド
オブジェクトのプロパティが関数である場合にそれをメソッドと呼ぶ、 一般的にはメソッドも含めたものを関数と言い、関数宣言などとプロパティである関数を区別する場合にメソッドと呼ぶ
code:method.js
const obj = {
// functionキーワードを使ったメソッド
method1: function() {
},
// Arrow Functionを使ったメソッド
method2: () => {
}
};
const obj = {
// メソッドの短縮記法で定義したメソッド
method() {
}
};
// call method
obj.method();
this
thisは関数が呼び出された時にその関数が所属していたオブジェクトを指す。
code:hello.js
const person = {
name: 'james',
say() {
console.log('hi ' + this.name);
}
};
person.say();
// => hi james
このthisはpersonオブジェクトである。メソッドが所属するオブジェクトのプロパティをオブジェクト名.プロパティ名 person.nameの代わりに、this.プロパティ名(this.name)で呼び出せる。
thisを含むメソッドを変数に代入した場合
関数.call(thisの値, ...関数の引数);