3 回答

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊
用關(guān)鍵字定義的函數(shù)function將有自己的this,而箭頭函數(shù)則沒有(doc)
因此,在您的情況下,當(dāng)您在示例 1 中使用箭頭函數(shù)時(shí),將this引用user,而在示例 2 中,this將引用getVideos
要解決此問題,您可以將this其存儲(chǔ)user到一個(gè)新變量中
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參考應(yīng)用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貢獻(xiàn)2037條經(jīng)驗(yàn) 獲得超6個(gè)贊
getVideos()在沒有上下文的情況下被調(diào)用,因此this指的是窗口對(duì)象。
解決此問題的首選方法是使用箭頭函數(shù),如第一個(gè)示例所示。
一個(gè)預(yù)箭頭功能的方法是做這樣的事情:
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貢獻(xiàn)1785條經(jīng)驗(yàn) 獲得超4個(gè)贊
在這里你應(yīng)該使用箭頭函數(shù)。這是使用 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>
添加回答
舉報(bào)