總結(jié):
- 純粹的函數(shù)調(diào)用:指向全局
- 作為對(duì)象方法的調(diào)用:指向?qū)ο螅ㄕ{(diào)用者)
- 構(gòu)造函數(shù)調(diào)用:構(gòu)造函數(shù)中的this指向new出來的對(duì)象實(shí)例
- apply調(diào)用:指向apply所接受的執(zhí)行空間
- 剪頭函數(shù):指向上一級(jí)
不重要的
- 定時(shí)器指向window
- 事件綁定指向元素本身
一道騰訊筆試題
var x = 20;
var a = {
x: 15,
fn: function () {
var x = 30;
return function () {
return this.x
}
}
}
console.log(a.fn());//返回一個(gè)函數(shù)
console.log((a.fn())());//20
console.log(a.fn()());//20
console.log(a.fn()() == (a.fn())()); //true
console.log(a.fn().call(this)); //20
console.log(a.fn().call(a)); //15
demo:
var name = 'tangbohu'
// 1.純粹的函數(shù)調(diào)用:指向全局
function doit() {
alert(this.name)//'tangbohu'
}
doit()
// 2.作為對(duì)象方法的調(diào)用:指向?qū)ο螅ㄕ{(diào)用者)
const person = {
name: 'xusheng',
sayName: function () {
alert(this.name)//xusheng
}
}
person.sayName()
// 3.構(gòu)造函數(shù)調(diào)用:構(gòu)造函數(shù)中的this指向new出來的對(duì)象實(shí)例
function foo(name, age) {
this.name = name
this.age = age
}
const baby = new foo('heshang', 13);
alert(baby.name)//heshang
// 4.apply調(diào)用:指向apply所接受的執(zhí)行空間
name = 'window-Name'
function testapply() {
alert(this.name)
}
testapply.apply(person)//xusheng 并不是window下的window-Name
// 5.剪頭函數(shù):指向上一級(jí)
const person2 = {
name: 'xusheng??????',
sayName: () => {
alert(this.name)//window-Name
}
}
person2.sayName()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。