0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Bind call and apply

Last updated at Posted at 2019-12-13

They are functions which function objects have.
Allows you to create preset function with arguments.

  • Call: Allows you to set this variable.
  • Apply: Similar to call but expects arguments as an array.
  • Bind: Also allows you to set the this variable. However, it does not execute the function immediately but generates a copy of the function which can be stored.
var john = {
  name: "John",
  age: 26,
  job: "Teacher",
  presentation: function(style, timeOfDay) {
    if (style === "formal") {
      console.log(
        "Good " +
          timeOfDay +
          ", Ladies and gentlemen! I'm " +
          this.name +
          ", I'm a " +
          this.job +
          " and I'm " +
          this.age +
          " years old"
      );
    } else if (style === "friendly") {
      console.log(
        "What's up? My name is " +
          this.name +
          ", I'm a " +
          this.job +
          " and I'm " +
          this.age +
          " years old"
      );
    }
  }
};

var emily = {
  name: "Emily",
  age: 35,
  job: "designer"
};

john.presentation("formal", "morning");

john.presentation.call(emily, "friendly", "afternoon");

// This is currying
var johnFriendly = john.presentation.bind(john, "friendly");

johnFriendly("afternoon");

Currying

Creating a function from another function but with some preset parameters.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?