this 是全域物件,在瀏覽器叫 window,在 node 叫 global。
在 JavaScript 裡 this 寫在哪沒有關係,跟怎麼執行有關。
const hero = {
name: "kk",
power: 100,
attack: function () {
console.log(this); //即使寫在這,也不知道是什麼
},
};
hero.attack(); //{name:"kk",power:100,attack:[Function:attack]}
//hero呼叫,所以this就是hero
function hi() {
console.log(this);
}
hi(); //沒有明確呼叫者,就是window
const hero = {
name: "kk",
power: 100,
attack: () => {
console.log(this);
},
};
hero.attack(); //箭頭函示->window
function hero(name, power) {
this.name = name;
this.power = power;
}
const h1 = hero("kk", 100); //沒有明確呼叫hero,this是window
const h1 = new hero("kk", 100); //this是{ }
const hero = {power:100}
function hi(){
console.log(this)
}
hi.apply(hero)//{power:100},會把hero當this帶進來
hi.call(hero)//{power:100},會把hero當this帶進來
const new_hi = hi.bind(hero); //會回傳一個新的function,不會馬上執行
new_hi()//{power:100}
hi.bind(hero)(); //{power:100},後面加上()會馬上執行IIFE
**apply與call差別**
const hero = {power:100}
function hi(msg){
console.log(msg)
console.log(this)
}
hi.apply(hero,[123])//123,逗號後是參數,apply參數要用陣列包
//{power:100}
hi.call(hero,123)//123,逗號後是參數
//{power:100}
"use strict";
function hi() {
console.log(this);
}
hi(); //undefined,不會是window