Js中的this

1.處于window上下文或者不在任何function中時,this指向window,不管當前是否處于use strict狀態(tài)
2.在一個function中調(diào)用this時,要看function如何被調(diào)用
①非strict mode,直接調(diào)用方法時,this指向window
function f1(){
return this;
}
console.log(f1()===window);//true
let f2=()=>{
return this;
}
console.log(f2()===window)//true
②strict mode,因為strict mode 規(guī)定,若沒有在調(diào)用時顯式指定this,則this為undefined
function f3(){
'use strict';
return this;
}
console.log(f3())//undefined
然而,在使用箭頭表達式時,隱式的指定調(diào)用為this,即window
let f4=()=>{
'use strict';
return this;
}
console.log(f4()===window)// true
3.調(diào)用時需要指定this時,使用call或者apply(僅在函數(shù)是function直接定義時使用,箭頭函數(shù)無此效果)
let custom={desc:'custom'}
let desc = 'window'
function normalWhatsThis(){
return this.desc;
}
let arrowWhatsThis=()=>{
return this.desc;
}
normalWhatsThis()//undefined
normalWhatsThis.call(custom)//"custom"
normalWhatsThis.apply(custom)//"custom"
// 箭頭表達式?jīng)]有這個效果
arrowWhatsThis()//undefined
arrowWhatsThis.call(custom)//undefined
arrowWhatsThis.apply(custom)//undefined
4.在調(diào)用函數(shù)時,使用bind可以綁定this
let foo={
desc:'foo'
}
let bar={
desc:'bar',
printMe : function(){
console.log(this.desc);
}
}
bar.printMe();// bar
let printFoo=bar.printMe.bind(foo);
printFoo()//foo
5.箭頭函數(shù)調(diào)用中,this指向當前未關閉的語法上下文的this(enclosing lexical context's this)
let global=this;
let test=(()=>this);
console.log(test()===this)//true
*使用call,bind或者apply調(diào)用箭頭函數(shù)時,第一個入?yún)缓雎?br> let custom2 = {
desc2:'custom'
}
let desc2 = 'window'

function arrowWhatsThis(){
return console.log(this.desc2);
}
arrowWhatsThis()// undefined
arrowWhatsThis.call(custom) // undefined
6.如果函數(shù)本身作為對象(object)的成員,則函數(shù)中的this指向方法被調(diào)用的對象
console.log('--------1-------');
let obj1={
a:3,
fn:function(){
console.log(this.a);
console.log(this===obj1);
}
}
obj1.fn()
console.log('--------------2-------');
let indiFn1=function(){
console.log(this.a);
console.log(this===obj2);

}
let obj2={
a:4,
fn:indiFn1
}
let obj4={
a:5,
fn:{}
}
obj2.fn();
obj4.fn=indiFn1;
obj4.fn();
console.log('-----------3---------------');
let indiFn2=()=>{
console.log(this.a);
console.log(this===obj2);

}
let obj3={
a:5,
fn:indiFn2
}
obj3.fn()
輸出:
--------1-------
3
true
--------------2-------
4
true
5
false
-----------3---------------
undefined
false
7.對象原型鏈中的this
let o = {
f:function(){
return this.a+this.b;
}
}
let p = Object.create(o);
p.a=3;
p.b=4;
console.log(p.f());//7

  • getter和setter的道理一致
    8.構造器中的this
    當一個方法被用作構造器,即方法是通過new關鍵詞調(diào)用時,this被綁定為構造的新對象
    function fn(){
    this.c=99
    }
    let obj = new fn();
    console.log(obj.c);//99
    9.作為dom事件的handler
    Dom事件的handler為function,則其中的this指向拋出事件的對象,即e.currentTarget
    <button id='btn' onclick="alert(this.tagName)">ClickMe</button>//BUTTON

引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容