gpt4 book ai didi

javascript - 关于 Javascript 中的对象方法

转载 作者:行者123 更新时间:2023-11-28 18:14:56 26 4
gpt4 key购买 nike

我正在尝试创建一个类方法,但我不知道我在这里做错了什么。这是我的代码

var Invoice = function(title) {
this.title = title;

this.addItem = function addItem(item_name) {
console.log("Hello, you added " + item_name);
};

invoice = new Invoice("Video games")
invoice.addItem('Xbox 360');

我收到以下错误:

TypeError at line undefined: invoice.addItem is not a function

最佳答案

简单的拼写错误,这说明了为什么正确的缩进至关重要:

var Invoice = function(title) {
this.title = title;
this.addItem = function addItem(item_name) {
console.log("Hello, you added " + item_name);
};
}; //you were not closing your constructor

您可以而且可能应该使用prototype

var Invoice = function(title) {
this.title = title;
};
Invoice.prototype.addItem = function(item_name){
console.log("Hello, you added " + item_name);
};

有关差异的详细说明,请参阅 JS - why use prototype

或者在 ES6 中,使用一个类:

class Invoice {
constructor(title){
this.title = title;
}
addItem(item_name) {
console.log("Hello, you added " + item_name);
}
}

如果您的发票是节点模块,并且您的问题由串联代码组成,请不要忘记添加:

module.exports = Invoice;

因此您可以在任何地方需要它。

在所有这些情况下,调用都是以相同的方式完成的:

let invoice = new Invoice("Video games") //or var if ES5
invoice.addItem('Xbox 360');

关于javascript - 关于 Javascript 中的对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40896040/

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