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

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

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>
添加回答
舉報