Skip to content

Instantly share code, notes, and snippets.

@cihat
Created November 16, 2020 09:25
Show Gist options
  • Save cihat/5b1f02a41ae507e761fb4c7c6811a2af to your computer and use it in GitHub Desktop.
Save cihat/5b1f02a41ae507e761fb4c7c6811a2af to your computer and use it in GitHub Desktop.
The apply() Method
The second function method you can use to manipulate this is apply(). The
apply() method works exactly the same as call() except that it accepts only
two parameters: the value for this and an array or array-like object of
parameters to pass to the function (that means you can use an arguments
object as the second parameter). So, instead of individually naming each
parameter using call(), you can easily pass arrays to apply() as the second
argument. Otherwise, call() and apply() behave identically. This example
shows the apply() method in action:
function sayNameForAll(label) {
console.log(label + ":" + this.name);
}
var person1 = {
name: "Nicholas"
};
var person2 = {
name: "Greg"
};
var name = "Michael";
sayNameForAll.apply(this, ["global"]); // outputs "global:Michael"
sayNameForAll.apply(person1, ["person1"]); // outputs "person1:Nicholas"
sayNameForAll.apply(person2, ["person2"]); // outputs "person2:Greg"
This code takes the previous example and replaces call() with
apply(); the result is exactly the same. The method you use typically
depends on the type of data you have. If you already have an array of
data, use apply(); if you just have individual variables, use call().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment