【发布时间】:2021-06-29 18:41:17
【问题描述】:
我正在学习 JavaScript,遇到了一个对于更有经验的人来说可能没什么大不了的问题,但这让我感到困惑。 所以,这是我正在做的一个非常基本的例子。我有两个文件,guitars.js 和 script.js。
吉他.js:
class Guitars {
constructor(brand, model, type) {
this.brand = brand;
this.model = model;
this.type = type;
}
changeDetails(newBrand, newModel, newType) {
this.brand = newBrand;
this.model = newModel;
this.type = newType;
}
}
export default Guitars
script.js:
import Guitars from "./guitars.js";
const newGuitar = new Guitars ("Epiphone", "Les Paul", "electric")
console.log("The new guitar: ", newGuitar)
我在一个 html 文件中有这个,像这样:
<script type="module" src="guitars.js" defer></script>
<script type="module" src="script.js" defer></script>
当我在浏览器中打开控制台时,我可以看到对象及其所有属性已创建,但我如何访问/调用该 changeDetails() 方法?
当我将所有内容放在同一个文件中时,我可以通过键入以下内容来访问所有内容:
newGuitar.changeDetails()
而且效果很好。当我把它分成模块时,我什么也做不了。
如果有人能帮我解决这个问题,我将不胜感激。
提前致谢。
【问题讨论】:
-
输入时看到的错误是什么:newGuitar.changeDetails('a','b','c');
-
嗨,首先,它不会像往常一样自动完成,如果我输入它并按回车键,我会收到以下红色消息:“未捕获的 ReferenceError:newGuitar 未在
中定义: 1:1" -
哦,你想在 chrome 控制台中访问它。我的错。看看这里发布的答案。
标签: javascript methods module class-method