0

Using the Function.Prototype.call example on the Mozilla Dev Network: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Why doesn't the example work when passing in an object literal instead of an argument array? The example should assign name and price to the Product prototype and return a Food and Toy object with the corresponding name and price fields, but the results come back undefined.

function Product(data) {
    this.name = data.name;
    this.price = data.price;

    if (price < 0)
         throw RangeError('Cannot create product "' + name + '" with a negative      price');
    return this;
}

function Food(data) {
    Product.call(this,data);
    this.category = 'food';
}
    Food.prototype = new Product();

function Toy(data) {
    Product.call(this,data);
    this.category = 'toy';
}
    Toy.prototype = new Product();

var cheese = new Food({ name: 'feta', price: 5 });
var fun = new Toy({ name: 'robot', price: 40 });

console.log(cheese);
console.log(fun);

In chrome I get a 'Uncaught TypeError: Cannot read property 'name' of undefined' error after the call function has passed reference to the Product.

4

1 回答 1

0

问题在这里:

Food.prototype = new Product();
// ...
Toy.prototype = new Product();

您在Product没有传递参数的情况下打电话。你应该Object.create改用。

Foo.prototype = Object.create(Product.prototype);
// ...
Toy.prototype = Object.create(Product.prototype);

这使您可以创建一个继承自另一个对象Product.prototype在本例中)的对象,而无需调用构造函数。


另外,这个:

if (price < 0)

应该是这样的:

if (this.price < 0)
于 2013-08-28T00:21:10.337 回答