this
関数の実行コンテキストのオブジェクト自身への参照が格納された暗黙の引数
const test = function () {
this.name = 'aichan';
console.log('`this` is', this);
};
const obj = new test(); //{ name: "aichan" }
この場合のthisは、{ name: "aichan"}オブジェクト。
暗黙的に渡されたthisのnameにaichanを突っ込んだ形。
const test = function () {
console.log('`this` is', this);
};
const obj = new test(); //test()
この場合のthisは、testオブジェクト。
new演算子は、
・関数オブジェクトをコピーし、新規にオブジェクトを作成する
・新規で作成したオブジェクトを暗黙の引数 thisとして渡している
ということを行っている。
const foo = {
name: 'Foo Object',
dump() {
console.log(this);
},
};
foo.dump(); // {name: 'Foo Object', dump: ƒ}
この場合のthisは、{name: 'Foo Object', dump: ƒ}というfooオブジェクト。
.の前のオブジェクトが暗黙の引数thisとして渡されている。
GoogleChromeのデバッグコンソールでthisと打つ。
this //Window {window: Window, self: Window, document: document, name: '', location: Location, …}
Windowオブジェクトがthisになっている。
実行環境のグローバルオブジェクトがthisとなる。
0 件のコメント:
コメントを投稿