关于Javascript中的Object方法

时间:2016-11-30 18:53:58

标签: javascript

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

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

1 个答案:

答案 0 :(得分:3)

简单的拼写错误,这表明为什么正确的缩进是必要的:

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');