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] あたらしいオブジェクトを作っているので元の関数に影響はない