質問

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.

役に立ちましたか?

解決

The issue is here:

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

You're calling Product without passing an argument. You should use Object.create instead.

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

This lets you make an object that inherits from another object (Product.prototype in this case), without having to invoke a constructor function.


Also, this:

if (price < 0)

should be this:

if (this.price < 0)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top