I understand how call (and apply) method works in the following example.
var Bob = {
name: "Bob",
greet: function() {
alert("Hi, I'm " + this.name);
}
}
var Alice = {
name: "Alice",
};
Bob.greet.call(Alice); // Hi, I'm Alice
From what I understand, what's happening above is he greet method of Bob object is invoked with the scope of Alice.
Can someone explain what is happening behind the scenes in the below example, where the call method is used on a constructor function which allows inheritance?
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
var chicken = new Food('chicken','40');
console.log(chicken); //{ name= "chicken", price="40", category="food"}
I can't make the connection between the first and second example, where the first example the call method is invoked on a function that is doing something (alert), whereas in the second example, the call method is used on a constructor function that is initializing some properties.