js中的this關(guān)鍵字指的是什么?
this:當(dāng)前方法執(zhí)行的主體(誰執(zhí)行的這個方法,那么this就是誰,所以this和當(dāng)前方法在哪創(chuàng)建的或者在哪執(zhí)行都沒有必然的關(guān)系)
判別js中this 關(guān)鍵字的幾個技巧
第一:給當(dāng)前元素的某個事件綁定方法,當(dāng)事件觸發(fā)方法執(zhí)行的時候,方法中的this 是當(dāng)前操作元素對象
oBox.onclick = fucntion () {
// => this 指的是oBox
}
第二:普通函數(shù)執(zhí)行,函數(shù)中的 this 取決于執(zhí)行的主體,誰執(zhí)行的, this 就是誰(執(zhí)行主體:非嚴(yán)格模式下,方法執(zhí)行,看方法名前面是否有 點(diǎn) ,有的話 點(diǎn) 前面是誰就是誰,沒有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í)行的時候,方法體中出現(xiàn)的 this 就是當(dāng)前函數(shù)這個類的實(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ù)中沒有this,this 是上下文中的 this
let obj = {
fn:function (){
//=> this:obj
setTimeout(()=>{
//=> this:obj;
},1000);
}
}
obj.fn();
第六:在小括號表達(dá)是中,會影響 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 第一個參數(shù)不寫或者寫null和undefined,this都是window,嚴(yán)格模式下寫誰就是誰,不寫就是undefined
第八:回調(diào)函數(shù)中一般 this 都是 window ,除非宿主函數(shù)執(zhí)行回調(diào)函數(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;
});