JavaScript:箭头函数中的 this 关键字访问问题

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();


开心每一天1111
浏览 113回答 3
3回答

茅侃侃

用关键字定义的函数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到getVideosconst 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()

阿晨1998

getVideos()在没有上下文的情况下被调用,因此this指的是窗口对象。解决此问题的首选方法是使用箭头函数,如第一个示例所示。一个预箭头功能的方法是做这样的事情:const user = {&nbsp; name: "Praveen",&nbsp; videos: ["html", "css", "js"],&nbsp; greet() {&nbsp; &nbsp; console.log(`welcome ${this.name}`);&nbsp; &nbsp; const that = this;&nbsp; // <---- that now refers to this context&nbsp; &nbsp; const getVideos = function () {&nbsp; &nbsp; &nbsp; console.log(`You have ${that.videos.length} videos`);&nbsp; &nbsp;// <--- use that instead of this&nbsp; &nbsp; };&nbsp; &nbsp; getVideos();&nbsp; },};

九州编程

在这里你应该使用箭头函数。这是使用 JavaScript 的 HTML 代码<!DOCTYPE html><html><head><script>&nbsp; &nbsp; &nbsp; &nbsp;const user = {&nbsp; &nbsp; &nbsp; name: "Praveen",&nbsp; &nbsp; &nbsp; videos: ["html", "css", "js"],&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; greet() {&nbsp; &nbsp; &nbsp; &nbsp; console.log(`welcome ${this.name}`);&nbsp; &nbsp; &nbsp; &nbsp; const getVideos = () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(`You have ${this.videos.length} videos`);&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; getVideos();&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; };&nbsp; &nbsp; user.greet();</script></head><body></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript