LoginSignup
17
11

More than 5 years have passed since last update.

JavaScriptのcall, apply, bind, ...スプレッド演算子について

Posted at

JavaScriptのcall, apply, bind, スプレッド演算子についてまとめてみた。

call

callは特定のオブジェクトの外からthisの値を指定することができます。
このメソッドはどの関数オブジェクトに対しても呼び出すことができます。

const object1 = {
  name: "yasu",
  email: "yyy@yyy.com"
}

function getName() {
  return this.name; // このままではundefinedになる。
}

console.log(getName()); // undefined
console.log(getName.call(object1)); // callによりobject1とthisが結び付けられる

output

undefined
yasu

次のようにobjectを書き換えることにも使えます

const object = {
  name: "yasu",
  email: "yyy@yyy.com"
}

function update(name, email) {
  this.name = name;
  this.email = email;
  return this;
}

console.log(update.call(object, "example", "example.example.com")); // 後ろの2つはupdateの引数

output

{name: "example", email: "example.example.com"}

apply

applyはcallと同じような働きをしますが引数の扱いが異なります
applyは引数を配列として受け取ります

const object = {
  name: "yasu",
  email: "yyy@yyy.com"
}

function update(name, email) {
  this.name = name;
  this.email = email;
  return this;
}

console.log(update.apply(object, ["example", "example.example.com"])); // 後ろの2つはupdateの引数

output

{name: "example", email: "example.example.com"}

スプレッド演算子(展開演算子)

スプレッド演算子(...)は、複数の引数、複数の要素を置かれる所で値を展開することができます。

上記例を使って例えると、

const object = {
  name: "yasu",
  email: "yyy@yyy.com"
}

const newObject = ["example", "example@example.com"];

function update(name, email) {
  this.name = name;
  this.email = email;
  return this;
}

console.log(update.call(object, ...newObject)); // 後ろの2つはupdateの引数

このようにcallを使ってapplyと同じように引数に配列を渡すことができるようになります。

bind

bindもthisの値を結びつけることができるのですが、その結びつきが永続的になります。

const object = {
  name: "yasu",
  email: "yyy@yyy.com"
}

const object2 = {
  name: "maruyama",
  email: "maruyama@aya.com"
}

const newObject = ["example", "example@example.com"];

function update(name, email) {
  this.name = name;
  this.email = email;
  return this;
}
const updateObject = update.bind(object);// objectがthisに永続的に結び付けられる
console.log(updateObject.apply(object2, newObject)); //object2をupdateしようとしても...
console.log(object2); // thisはobjectに紐付いているためupdateされない。

output

{name: "example", email: "example@example.com"}
{name: "maruyama", email: "maruyama@aya.com"}

参考 初めてのJavaScript

17
11
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
17
11