亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JavaScript:箭頭函數中的 this 關鍵字訪問問題

JavaScript:箭頭函數中的 this 關鍵字訪問問題

開心每一天1111 2023-04-20 17:13:53
const user = {    name: "Praveen",    videos: ["html", "css", "js"],        greet() {        console.log(`welcome ${this.name}`);        const getVideos = () => {            console.log(`You have ${this.videos.length} videos`);        };        getVideos();      },    };user.greet();我可以訪問videos.length上面代碼中的值(我使用了箭頭函數),但我無法訪問videos.length下面代碼中的值:const user = {    name: "Praveen",    videos: ["html", "css", "js"],        greet() {        console.log(`welcome ${this.name}`);        const getVideos = function () {          console.log(`You have ${this.videos.length} videos`);        };        getVideos();      },    };user.greet();
查看完整描述

3 回答

?
茅侃侃

TA貢獻1842條經驗 獲得超21個贊

用關鍵字定義的函數function將有自己的this,而箭頭函數則沒有(doc)


因此,在您的情況下,當您在示例 1 中使用箭頭函數時,將this引用user,而在示例 2 中,this將引用getVideos


要解決此問題,您可以將this其存儲user到一個新變量中


const user = {

  name: "Praveen",

  videos: ["html", "css", "js"],


  greet() {

    console.log(`welcome ${this.name}`)

    const self = this // notice me

    const getVideos = function () {

      console.log(`You have ${self.videos.length} videos`)

    }

    getVideos()

  },

}

user.greet()

或者使用call然后將this參考應用user到getVideos


const user = {

  name: "Praveen",

  videos: ["html", "css", "js"],


  greet() {

    console.log(`welcome ${this.name}`)

    const getVideos = function () {

      console.log(`You have ${this.videos.length} videos`)

    }

    getVideos.call(this) // notice me

  },

}

user.greet()


查看完整回答
反對 回復 2023-04-20
?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

getVideos()在沒有上下文的情況下被調用,因此this指的是窗口對象。


解決此問題的首選方法是使用箭頭函數,如第一個示例所示。


一個預箭頭功能的方法是做這樣的事情:


const user = {

  name: "Praveen",

  videos: ["html", "css", "js"],


  greet() {

    console.log(`welcome ${this.name}`);

    const that = this;  // <---- that now refers to this context

    const getVideos = function () {

      console.log(`You have ${that.videos.length} videos`);   // <--- use that instead of this

    };

    getVideos();

  },

};


查看完整回答
反對 回復 2023-04-20
?
九州編程

TA貢獻1785條經驗 獲得超4個贊

在這里你應該使用箭頭函數。這是使用 JavaScript 的 HTML 代碼


<!DOCTYPE html>

<html>

<head>

<script>

       const user = {

      name: "Praveen",

      videos: ["html", "css", "js"],

    

      greet() {

        console.log(`welcome ${this.name}`);

        const getVideos = () => {

          console.log(`You have ${this.videos.length} videos`);

        };

        getVideos();

      },

    };

    user.greet();

</script>

</head>

<body>


</body>

</html>


查看完整回答
反對 回復 2023-04-20
  • 3 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號