Loading lesson path
method lets you write a method that can be used on different objects.
method is used to call a function with a specific this.
method is similar to call(), but it passes arguments in an array. apply() is an advanced topic.
before continuing.
method is used to call a function with an object as an argument.
method takes this as the first argument. The second argument is an array of values passed to the function.
method is similar to the call() method (previous chapter). Syntax functionName.apply(
this, [arg1, arg2, ...]);' When you use apply(), you can decide what this should refer to. In the example below, the greet function returns a greeting + this.name. When you use apply(), you decide that this should be the person3 object.
const person1 = { name: "John" };
const person2 = { name: "Paul" };
const person3 = { name: "Ringo" };
function greet(greeting) {
return greeting + " " + this.name;
}
greet.apply(person3, ["Hello"]);and call() is how arguments are passed.
method takes arguments separately.
method takes arguments as an array.
when your arguments are already stored in an array.
Example greet.call(person, "Hello");
greet.apply(person, ["Hello"]);to borrow a method from another object:
Apply the fullName method of person on person1
// Create a person Object const person = {fullName
: function() {
return this.firstName + " " + this.lastName;
}
}
// Create a person1 Object const person1 = {
firstName:"John", lastName: "Doe"
}
// Create a person2 Object const person2 = {
firstName:"Mary", lastName: "Doe"
}
// This will return "John Doe":
person.fullName.apply(person1
);
In these 2 examples, the apply() method behaves exactly the same as the call() method.Apply the fullName method of person on person2
// Create a person Object const person = {fullName
: function() {
return this.firstName + " " + this.lastName;
}
}
// Create a person1 Object const person1 = {
firstName:"John", lastName: "Doe"
}
// Create a person2 Object const person2 = {
firstName:"Mary", lastName: "Doe"
}
// This will return "Mary Doe"
person.fullName.call(person2
);