LoginSignup
2
2

More than 5 years have passed since last update.

bind

Last updated at Posted at 2012-09-22

JavaScript.Next Returns のスライドを読んでいて
Function.prototype.bind がよくわからなかったので書いてみました。
MDN の bind のページ も参考にしました。
ブラウザのコンソールに張り付ければ実行できます。

bind_sample.js
// Callback でも this を継承
var test = {
    msg: 'hello from test',
    hello: function () {
        console.log(this);
        console.log(this.msg);
    }
};
setTimeout(test.hello, 1000); // bind しないと this は window オブジェクト
setTimeout(test.hello.bind(test), 1000);

// メソッドを関数に
var slice = Function.prototype.call.bind(Array.prototype.slice);
var toArray = function () {
    return slice(arguments);
};
var ret = toArray(1, 2, 'foo');
console.log(ret); // -> [1, 2, 'foo']
console.log(Array.isArray(ret)); // -> true

// 引数を固定
var toArray2 = toArray.bind(undefined, 1000, 2000);
console.log(toArray2(1, 2, 3, 4)); // -> [1000, 2000, 1, 2, 3, 4]
console.log(toArray(1, 2, 3, 4)); // -> [1, 2, 3, 4] あたらしいオブジェクトを作っているので元の関数に影響はない
2
2
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
2