tholapz
tholapz

Reputation: 3

what is the difference between this two constructors in JavaScript?

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;
}

Upvotes: 0

Views: 85

Answers (2)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

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

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22405

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.

Upvotes: 1

Related Questions