對(duì)于function中的this诅岩,需要明確一點(diǎn)的是它只有在function執(zhí)行的時(shí)候才能被確定邪锌。并且this指的是function的執(zhí)行環(huán)境楣铁,也就是調(diào)用該方法的對(duì)象道偷。
var user = {
count:1,
getCount:function(){
return this.count;
}
}
console.log(user.getCount()); //1
var otherGetCount = user.getCount;
console.log(otherGetCount()); //undefined;
上面代碼中獎(jiǎng)getCount方法賦值給otherGetCount方法缀旁,當(dāng)在全局環(huán)境中調(diào)用otherGetCount()方法時(shí),此方法的執(zhí)行環(huán)境為window勺鸦。由于在window下未定義count,所以返回值為undefined并巍。
可通過以下代碼驗(yàn)證:
var count = 2;
var user = {
count:1,
getCount:function(){
return this.count;
}
}
console.log(user.getCount()); //1
var otherGetCount = user.getCount;
console.log(otherGetCount()); //2;