Here i have two example which has two constructor Product
and Food
.In my first example Food constrcutor inherits from Products via Food.prototype=new Product();
when i console.log chicken object created by Food constructor in shows it properties on the console:
Food {category: "food", name: newname, price: newprice}
here is the code:
<html>
<body>
<script>
function Product(name, price) {
this.name = name;
this.price =price;
}
function Food(name, price) {
this.category = 'food';
}
Food.prototype=new Product('newname','newprice');
var chicken = new Food('chicken','40');
console.log(chicken);
</script>
</body>
</html>
Now here is the second example where i removed the Food.prototype=new Products('newname,'newprice');
and instead i used Product.apply(this,arguments);
inside Food constructor.in the console it shows the same result:
Food {name: "chicken", price: "40", category: "food"}
Code:
<html>
<body>
<script>
function Product(name, price) {
this.name = name;
this.price =price;
}
function Food(name, price) {
Product.apply(this,arguments);
this.category = 'food';
}
var chicken = new Food('chicken','40');
console.log(chicken);
</script>
</body>
</html>
What confusing me is in both examples, chicken object has three properties category,name and price.Though in the second example Food is not inheriting from Product.I mean Product is not on the prototype chain of Food.So whats the difference between the two??Which one to use when??i am quite new to object oriented concept .So detailed explanation would be great!!!