1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        Nodejs中的this

        共 1230字,需瀏覽 3分鐘

         ·

        2021-04-12 10:12

        以下內容都是關于在nodejs中的this而非JavaScript中的this,nodejs中的this和在瀏覽器中JavaScript中的this是不一樣的。

        在全局中的this

        console.log(this); {}this.num = 10;console.log(this.num); 10console.log(global.num); undefined

        全局中的this默認是一個空對象。并且在全局中this與global對象沒有任何的關系,那么全局中的this究竟指向的是誰?在本章節(jié)后半部分我們會講解。

        在函數中的this

        function fn(){    this.num = 10;}fn();console.log(this); {}console.log(this.num); undefinedconsole.log(global.num); 10

        在函數中this指向的是global對象,和全局中的this不是同一個對象,簡單來說,你在函數中通過this定義的變量就是相當于給global添加了一個屬性,此時與全局中的this已經沒有關系了。

        如果不相信,看下面這段代碼可以證明。

        function fn(){    function fn2(){        this.age = 18;    }    fn2();    console.log(this); global    console.log(this.age); 18    console.log(global.age); 18}fn();

        對吧,在函數中this指向的是global。

        構造函數中的this

        function Fn(){    this.num = 998;}var fn = new Fn();console.log(fn.num); 998console.log(global.num); undefined

        在構造函數中this指向的是它的實例,而不是global。

        我們現(xiàn)在可以聊聊關于全局中的this了,說到全局中的this,其實和Nodejs中的作用域有一些關系。

        回到正題,全局中的this指向的是module.exports。

        this.num = 10;console.log(module.exports); {num:10}console.log(module.exports.num);
        為什么在全局中this會指向module.exports,那就需要先了解更多關于module.exports的相關知識了,暫時我們先了解到這里,后面有機會我們會聊到module。

        學習更多技能

        請點擊下方公眾號


        瀏覽 30
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            成人在线不卡 | 四虎做爱 | 激情男女呻吟一进一出 | 2024国产无码 | 咪咪色色天天干 | 我和三个小婕子做受 | 国产精品综合激情 | 国产女人18水真多18精品 | 精品少妇一区二区三区在线观看 | 久久免费成人 |