gpt4 book ai didi

javascript - 很难在控制台日志中显示对象内部的功能

转载 作者:行者123 更新时间:2023-12-01 15:55:27 25 4
gpt4 key购买 nike

我是 JS 的新手,对于这个可能很愚蠢的问题深表歉意。我正在学习对象构造函数语法,但我对为什么控制台日志不显示作为该对象一部分的函数的结果感到困惑。这是代码:

var sportsCar = {
name: "Lamborghini",
color: "red",
horsepower: "100mph",
electric: true,
showModelName: function() {
return(this.name);
console.log(this.name);
}
};

将这个对象输入开发者工具后的结果是空白,我以为它会说“Lamborghini”。我考虑过将 console.log(showModelName) 放在对象之外,但记得该函数不是全局范围的。谁能解释为什么控制台日志不显示名称?

最佳答案

不确定您到底想做什么,但似乎有两个问题,首先是因为您在记录之前 return,并且因为您仍然需要使用 this。 showModelName,不仅仅是 showModelName

return(this.name); // nothing after this line will run
console.log(showModelName);

var sportsCar = {
name: "Lamborghini",
color: "red",
horsepower: "100mph",
electric: true,
showModelName: function() {
console.log(this.showModelName);
return(this.name);
}
};

console.log(sportsCar.showModelName())

关于javascript - 很难在控制台日志中显示对象内部的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62886249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com