js中的this關(guān)鍵字指的是什么?
this:
當(dāng)前方法執(zhí)行的主體(誰(shuí)執(zhí)行的這個(gè)方法勿锅,那么this就是誰(shuí),所以this和當(dāng)前方法在哪創(chuàng)建的或者在哪執(zhí)行都沒(méi)有必然的關(guān)系)
判別js中this
關(guān)鍵字的幾個(gè)技巧
第一:給當(dāng)前元素的某個(gè)事件綁定方法枣氧,當(dāng)事件觸發(fā)方法執(zhí)行的時(shí)候溢十,方法中的this
是當(dāng)前操作元素對(duì)象
oBox.onclick = fucntion () {
// => this 指的是oBox
}
第二:普通函數(shù)執(zhí)行,函數(shù)中的 this
取決于執(zhí)行的主體达吞,誰(shuí)執(zhí)行的张弛, this
就是誰(shuí)(執(zhí)行主體:非嚴(yán)格模式下,方法執(zhí)行酪劫,看方法名前面是否有 點(diǎn)
吞鸭,有的話 點(diǎn)
前面是誰(shuí)就是誰(shuí),沒(méi)有this
就是 window
覆糟,嚴(yán)格模式下 this
是 undefined
)
function fn (){
console.log(1);
}
var obj = {
fn:fn;
};
//執(zhí)行的是相同的方法
obj.fn(); //函數(shù)的this是obj
fn(); //函數(shù)的this是window
第三:自執(zhí)行函數(shù)中的 this
是 window
~function(){
//自執(zhí)行函數(shù)中的this是window
}();
第四:構(gòu)造函數(shù)執(zhí)行的時(shí)候刻剥,方法體中出現(xiàn)的 this
就是當(dāng)前函數(shù)這個(gè)類的實(shí)例。
function Fn(name,age){
var n = 10;
this.name = name; //=> this是當(dāng)前類的實(shí)例
this.age = age + n; //=> this是當(dāng)前類的實(shí)例
}
var f = new Fn();
第五:箭頭函數(shù)中沒(méi)有this
滩字,this
是上下文中的 this
let obj = {
fn:function (){
//=> this:obj
setTimeout(()=>{
//=> this:obj;
},1000);
}
}
obj.fn();
第六:在小括號(hào)表達(dá)是中透敌,會(huì)影響 this
執(zhí)向
let obj = {
fn:function (){
}
}
obj.fn(); //=> this:obj
(12,obj.fn)(); //=> this:window
第七:使用 call / apply / bind
可以改變 this
執(zhí)向
代碼實(shí)例
let obj = {
fn:function (){
}
}
fn.call(obj); //=> this:obj
fn.call(12); //=> 12
fn.call(); //=>this:window 非嚴(yán)格模式下 call / apply / bind 第一個(gè)參數(shù)不寫或者寫null和undefined盯滚,this都是window,嚴(yán)格模式下寫誰(shuí)就是誰(shuí)酗电,不寫就是undefined
第八:回調(diào)函數(shù)中一般 this
都是 window
,除非宿主函數(shù)執(zhí)行回調(diào)函數(shù)的時(shí)候把 this
特殊指向了(箭頭函數(shù)除外:箭頭函數(shù)中的 this
是它上下文)
代碼實(shí)例
let fn = (callback)=>{
callback && callback();
//type of callback === 'function' ? callback():null;
let res = callback(10,20);
console.log(res);
}
fn((n,m)=>{
//=> this:window
console.log(n,m);
return n + m;
});