You can use call
/ apply
methods to invoke a function immediately.
call
and apply
methods serve to the same purpose. They call a function with given this
value and arguments. While the syntax of both functions is almost same, the main difference is that call
accepts arguments as an argument list, however apply
accepts a single array of arguments.Check out the code below to see how call
method is used.
function Animal(name, hasWings) {
this.name = name;
this.hasWings = hasWings;
}
function Bird(name, hasWings) {
Animal.call(this, name, hasWings);
this.canFly = false;
}
console.log(new Bird('Chicken', true).name);
Check out the code below to see how apply
method is used.
function Animal(name, hasWings) {
this.name = name;
this.hasWings = hasWings;
}
function Bird(name, hasWings) {
Animal.apply(this, [name, hasWings]);
this.canFly = false;
}
console.log(new Bird('Chicken', true).name);