2
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?

bindはthisだけじゃない − 引数を事前に固定する部分適用という使い方

2
Last updated at Posted at 2026-04-02

はじめに

bindってthisを固定するやつでしょ——そう思っていませんか?

実はbindには、引数を事前に固定するという使い方もあります。
この記事では、thisバインドをサクッとおさらいしたあと、
あまり知られていない「部分適用」という使い方を紹介します。

thisバインドのおさらい

JavaScriptでは、thisの参照先は呼び出し方によって変わります。

const user = {
  name: 'Taro',
  greet() {
    console.log(`Hello, ${this.name}`);
  }
};

const greet = user.greet;
greet(); // → Hello, undefined(thisがwindow/undefinedになる)

bindを使うと、thisの参照先を固定した新しい関数を作れます。

const boundGreet = user.greet.bind(user);
boundGreet(); // → Hello, Taro

これはご存知の方も多いと思います。次からが本題です。

bindのシグネチャを確認する

bindの構文を改めて確認してみましょう。

func.bind(thisArg, arg1, arg2, ...)

第1引数にthisとして使う値を渡すのはご存知の通りです。
しかし、第2引数以降にも値を渡せます

これが何を意味するのか、次のセクションで説明します。

部分適用:引数を事前に固定する

bindの第2引数以降に値を渡すと、その値が関数の引数として事前に固定されます。
これを「部分適用」と呼びます。

例として、2つの数を掛け合わせる関数を使います。

function multiply(x, y) {
  return x * y;
}

bind(null, 2)とすることで、x2に固定した新しい関数を作れます。
thisが不要な場合は第1引数にnullを渡します)

const double = multiply.bind(null, 2);

console.log(double(3)); // → 6
console.log(double(5)); // → 10

doubleは「x2で固定されたmultiply」です。
yだけを渡せば動作します。

同様に、x3に固定したtripleも作れます。

const triple = multiply.bind(null, 3);

console.log(triple(4)); // → 12

一度作った関数を「固定値違い」で再利用できるのが部分適用の強みです。

まとめ

bindには2つの使い方があります。

使い方 概要
thisバインド thisの参照先を固定した新しい関数を作る
部分適用 引数を事前に固定した新しい関数を作る

thisバインドだけがbindではありません。
部分適用を知っておくと、既存の関数を柔軟に再利用できる場面が増えます。

2
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
2
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?