LoginSignup
1
3

More than 5 years have passed since last update.

this参照

Posted at

this参照とは

  • JSのどこでも使える読み込み専用の変数
  • this参照はオブジェクトを参照する

this参照の規則4種

thisが使用される場所 参照されるオブジェクト
トップレベルコード グローバルオブジェクト
コンストラクタ呼び出し インスタンスオブジェクト
メソッド呼び出し レシーバオブジェクト
apply,call呼び出し 引数で指定したオブジェクト

一番わかりやすいのはこちらの記事
JavaScriptの「this」は「4種類」??

メソッド呼び出し

js
const obj = {
  value: 10,
  show: function() {
    console.log(this.value);
  }
}
obj.show(); // 10
//thisはobjのことを指す。

トップレベルコード

トップレベルコードのthis参照はグローバルオブジェクト
関数内で呼ばれていも、thisはグローバル変数を参照する

js
const str = "global";
console.log(this.str);
//global

function fn() {
    const str = "local";
    console.log(this.str); 
    console.log(str); 
}
fn();
//global
//local 

コンストラクタ呼び出し

生成されたインスタンス自身がthisにsetされる

js
function MyClass(x, y) {
  this.x = x;
  this.y = y;
}

const obj = new MyClass(5, 10);
const obj2 = new MyClass(1, 2);

console.log(obj.x)//5
console.log(obj2.x)//1

apply call

引数に指定したオブジェクトをthis参照にできる。
好きにthisを設定できる。

js
function MyClass(x, y) {
  this.x = x;
  this.y = y;
}

MyClass.prototype.show = function() {
  console.log(this.x, this.y);
}

const obj = new MyClass(5, 10);
const obj2 = new MyClass(1, 2);

obj.show.call(obj2);
//1 2

applyとcallの違い

  • applyは第二引数に配列を取る
  • callは第二引数以降がそのまま渡される。
js
var myObject = {
  add: function(value1, value2) {
    console.log(this.value + value1 + value2);
  }
};
var yourObject = {
  value: 3
};

myObject.add.apply(yourObject, [2, 10]); // 15
myObject.add.call(yourObject, 2, 10); // 15
1
3
1

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
3