在JavaScript中添加原型对象的方法

时间:2018-02-08 04:14:59

标签: javascript

我正在通过Murach’s JavaScript and jQuery (3rd Edition),并且我在本书的代码中遇到了编译错误。我已经根据书的语法对我的语法进行了三重检查,我想我可以排除它。我还查看了errata page,但我找不到对我所在页面的引用。

我也看了this question,但我没有找到适用于我的问题的任何内容。

这是我的对象构造函数:

var Invoice = function(subtotal, taxRate) {
    this.subtotal = subtotal;
    this.taxRate = taxRate;
};

尝试向原型对象添加方法时遇到了麻烦:

// The getTaxAmount method is added to the Invoice prototype
Invoice.prototype.getTaxAmount: function() {
// Compiler whines right here ^ and     ^
    return (subtotal * this.taxRate);
};

// The getInvoiceTotal method is added to the Invoice prototype
Invoice.prototype.getInvoiceTotal: function() {
// Compiler whines right here ^ and     ^
    return subtotal + this.getTaxAmount(this.subtotal);
};

我使用Visual Studio Code with Debugger for Chrome。 VS Code中的提示表示它希望在其投诉的第一个位置;,并在其抱怨的第二个位置[js] identifier expected

感谢您的阅读。我欢迎你的建议。

5 个答案:

答案 0 :(得分:2)

语法是

Invoice.prototype.getInvoiceTotal = function() {}

这是因为prototype本身就是一个对象。

答案 1 :(得分:1)

是的,这是一个语法错误。您更愿意使用赋值运算符=来完成此类工作:

// The getTaxAmount method is added to the Invoice prototype
Invoice.prototype.getTaxAmount = function() {
    return (subtotal * this.taxRate);
};

// The getInvoiceTotal method is added to the Invoice prototype
Invoice.prototype.getInvoiceTotal = function() {
    return subtotal + this.getTaxAmount(this.subtotal);
};

除此之外,您还可以使用Object.assign为对象分配属性,如下所示:

Object.assign(Invoice.prototype, {
    getTaxAmount: function() {
        return (subtotal * this.taxRate);
    },
    getInvoiceTotal: function() {
        return subtotal + this.getTaxAmount(this.subtotal);
    }
});

请注意,在使用后者时,您不会在函数末尾使用分号。

答案 2 :(得分:0)

根据w3Schools,将函数添加到原型的正确方法如下:

Invoice.prototype.getInvoiceTotal = function(){ **your fx here** };

从外观上看,你使用的是:而不是=,这可能会让你感到悲伤。

答案 3 :(得分:0)

尝试使用等号。冒号用于JSON的变量值。

Invoice.prototype.getInvoiceTotal = function() {
// Compiler whines right here ^ and     ^
    return subtotal + this.getTaxAmount(this.subtotal);
};

答案 4 :(得分:0)

  

所有JavaScript对象都从原型继承属性和方法。

     

JavaScript prototype属性还允许您添加新方法对象构造函数:

ie:Date对象从Date.prototype继承。数组对象继承自Array.prototype。 Person对象继承自Person.prototype。

<script>
  var Invoice = function(subtotal, taxRate) {
  this.subtotal = subtotal;
  this.taxRate = taxRate;
};

Invoice.prototype.getTaxAmount = function() {
    return (subtotal * this.taxRate);
};

var myTax= new Invoice(10,5);
document.getElementById("demo").innerHTML =
"My tax amount is " + myTax.getTaxAmount (); 
</script>