溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

關(guān)于JavaScript中的this指向問題總結(jié)篇

發(fā)布時間:2020-09-08 21:07:13 來源:腳本之家 閱讀:129 作者:PR都像梅超風(fēng) 欄目:web開發(fā)

在javascript中this的指向一直是前端同事的心頭病,也同時是各面試題的首選,現(xiàn)在我們就來總結(jié)一下js中this的指向。首先需要了解一下幾個概念:

1:全局變量默認(rèn)掛載在window對象下

2:一般情況下this指向它的調(diào)用者

3:es6的箭頭函數(shù)中,this指向創(chuàng)建者,并非調(diào)用者

4:通過call、apply、bind可以改改變this的指向

下面我們具體分析一下

1:在函數(shù)調(diào)用時

 ?。ǚ菄?yán)格模式)

const func = function () {
    console.log(this);
    const func2 = function () {
      console.log(this);
    };
    func2(); //Window
  };
  func(); //Window

  ?。▏?yán)格模式)

'use strict'
  const func = function () {
    console.log(this);
    const func2 = function () {
      console.log(this);
    };
    func2(); //undefined
  };
  func(); //undefined

     結(jié)合第四和第一兩條規(guī)則:func這個函數(shù)是全局的,默認(rèn)掛載在window對象下,this指向它的調(diào)用者即window,所以輸出window對象,但是在嚴(yán)格模式下,this不允許指向全局變量window,所以輸出為undefined(func2在函數(shù)直接調(diào)用時默認(rèn)指向了全局window,其實這屬于javascript設(shè)計上的缺陷,正確的設(shè)計方式是內(nèi)部函數(shù)的this 應(yīng)該綁定到其外層函數(shù)對應(yīng)的對象上,為了規(guī)避這一設(shè)計缺陷,聰明的 JavaScript 程序員想出了變量替代的方法,約定俗成,該變量一般被命名為 that。這種方式在接下來會講到)。

2:作為對象方法

const user = {

    userName: '小張',
    age: 18,
    selfIntroduction: function () {
      const str = '我的名字是:' + this.userName + ",年齡是:" + this.age;
      console.log(str);

      const loop = function () {
        console.log('我的名字是:' + this.userName + ",年齡是:" + this.age);
      };

      loop();   //我的名字是:undefined,年齡是:undefined

    }
  };

  user.selfIntroduction();  //我的名字是:小張,年齡是:18

    按照咱的第一條規(guī)則,this指向他的調(diào)用者,selfIntroduction()方法的調(diào)用者是user,所以在selfIntroduction()方法內(nèi)部this指向了他的父對象即user,而loop方法輸出的為undefined的原因就是我在上面所說的javascript的設(shè)計缺陷了,在這種情況下,我們通常選擇在selfIntroduction()方法里將this緩存下來。

const user = {
    userName: '小張',
    age: 18,
    selfIntroduction: function () {
      const str = '我的名字是:' + this.userName + ",年齡是:" + this.age;
      console.log(str);

      const that=this;

      const loop = function () {
        console.log('我的名字是:' + that.userName + ",年齡是:" + that.age);
      };

      loop();   //我的名字是:小張,年齡是:18

    }
  };

  user.selfIntroduction();  //我的名字是:小張,年齡是:18

此時loop的this指向就理想了。

const user={

    userName:'小張',
    age:18,
    selfIntroduction:function(){
      const str='我的名字是:'+this.userName+",年齡是:"+this.age;
      console.log(str); 
    }
  };

  const other =user.selfIntroduction;
  other(); //我的名字是:undefined,年齡是:undefined

  const data={
    userName:'小李',
    age:19,
  };
  data.selfIntroduction=user.selfIntroduction;
  data.selfIntroduction(); //我的名字是:小李,年齡是:19

  在看這段代碼,將selfIntroduction()賦值給了全局變量other,調(diào)用other()方法,other掛載在全局函數(shù)window對象下,window對象下沒有userName 和 age 這兩個屬性,所以輸出為undefined。第二段代碼,申明了data對象,包含了username和age屬性,記住我們的第二條規(guī)則一般情況下this指向它的調(diào)用者,大家就明白了,data是selfIntroduction()的函數(shù)的調(diào)用者,所以輸出了data的userName和age。

3:在html里作為事件觸發(fā)

<body>
  <div id="btn">點擊我</div>
</body>
     const btn=document.getElementById('btn');
    btn.addEventListener('click',function () {
      console.log(this); //<div id="btn">點擊我</div>
    })

在種情況其實也是遵循了第二條規(guī)則一般情況下this指向它的調(diào)用者,this指向了事件的事件源即event。

4:new關(guān)鍵字(構(gòu)造函數(shù))

const fun=function(userName){
    this.userName=userName;
  }
  const user=new fun('郭德綱');  
  console.log(user.userName); //郭德綱

 這個就不多贅述了,new關(guān)鍵字構(gòu)造了一個對象實例,賦值給了user,所以userName就成為了user對象的屬性。

5:es6(箭頭函數(shù))

const func1=()=>{
    console.log(this); 
  };
  func1(); //Window
const data={
    userName:'校長',
    selfIntroduction:function(){
      console.log(this); //Object {userName: "校長", selfIntroduction: function}
      const func2=()=>{
        console.log(this); //Object {userName: "校長", selfIntroduction: function}
      }

      func2();
    }
  }
  data.selfIntroduction();

  大家在看看我開頭說的第三條準(zhǔn)則:es6的箭頭函數(shù)中,this指向創(chuàng)建者,并非調(diào)用者,fun1 在全局函數(shù)下創(chuàng)建,所以this指向全局window,而fun2在對象data下創(chuàng)建,this指向data對象,所以在func2函數(shù)內(nèi)部this指向data對象,個人認(rèn)為es6的箭頭函數(shù)的this指向是對我上面所說的javascript設(shè)計缺陷的改進(jìn),(個人認(rèn)知)。

6:改變this的指向

  call、apply、bind這三個函數(shù)是可以人為的改變函數(shù)的this指向的,在這里就不多說這三者的區(qū)別了,在往后的博客里我會詳細(xì)解釋這三者的區(qū)別的?,F(xiàn)在先拿一個來舉一個例子

const func=function(){
   console.log(this);
 }; 
 func(); //window
 func.apply({userName:"郭德綱"}); //Object {userName: "郭德綱"}

   這三個方法都是可以人為的改變this的指向,區(qū)別是call、apply會將該方法綁定this之后立即執(zhí)行,而bind方法會返回一個可執(zhí)行的函數(shù)。

說這很多總結(jié)起來就是我開頭說的4點

1:全局變量默認(rèn)掛載在window對象下

2:一般情況下this指向它的調(diào)用者

3:es6的箭頭函數(shù)中,this指向創(chuàng)建者,并非調(diào)用者

4:通過call、apply、bind可以改改變this的指向

說實話第一次寫博客,確實挺忐忑的,會不會有人看我的博客?會不會寫的不正確?……想好多了,總結(jié)了:不好的地方歡迎指正。

以上所述是小編給大家介紹的關(guān)于JavaScript中的this指向問題總結(jié)篇,希望對大家有所幫助,如果大家有任何問題,歡迎給我留言,小編會及時回復(fù)大家的!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI