Question

on MDN's page for Call there is an example of 3 constructors: Product, Food, and Toy

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

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

function Food(name, price) {
    Product.call(this, name, price);
    this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);

Why is this line necessary?

Food.prototype = Object.create(Product.prototype);

Can't I just simply do this?

function Food (name, price) {
    var me = Product.call(this, name, price);
    me.category = 'food';
    return me;
}
Was it helpful?

Solution

One difference is the syntax. In my opinion, it is better in the first snippet.

Basically this :

Food.prototype = Object.create(Product.prototype);

and later on this

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

mean that they share the same prototype of product, which is nice. But in the example you are showing us, they aren't really exploiting the class concept which is not really present in JavaScript, but active in must langage (like PHP for example).

You could have function or properties attached only to a toy or food :

Food.prototype = Object.create(Product.prototype);
Food.prototype.eat = function(){ //Toy object can't call that function
    alert('Om Nom Nom')
}

Of course you could do that as well :

function Food (name, price) {
    var me = Product.call(this, name, price);
    me.category = 'food';
    me.eat = function(){
        alert('Om Nom Nom');
    };
    return me;
}

But that lead to an unneeded memory usage and may affect performance.

Lastly, the use of instanceof will be wrong. With the second method, you will be unable to know if you object is a product:

//Method1
alert(foodObj instanceof Food); //true
alert(foodObj instanceof Product); //true

//Method2
alert(foodObj instanceof Food); //true
alert(foodObj instanceof Product); //false

Live example

OTHER TIPS

The difference is that your object Food will not inherit the prototype methods of Product. It returns what looks like to be an instance of Product but there are differences.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top