I'm trying to understand the call and apply methods in javascript. But I didn't understand why I should use it.
var person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
var person2 = {
firstName:"Mary",
lastName: "Doe"
}
var x = person.fullName.call(person1);
I can do this example without using call and apply.
var person = {
fullName: function(firstName, lastName) {
return firstName + " " + lastName;
}
}
var person1 = {
firstName:"John",
lastName: "Doe"
}
var person2 = {
firstName:"Mary",
lastName: "Doe"
}
var x = person.fullName(person1.firstName, person1.lastName);
Or I don't understand this example.
function Product(name) {
this.name = name;
}
function Pizza(name) {
Product.call(this,name);
}
const pizza = new Pizza("Margherita");
When I think of this example, I can do with the prototype. Why use call or apply? Thank you
.callso thethiscontext of a method is called in another context outside of its original context. By the way, using prototype in the last example would also be a waste if you just want anew Product.