Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
var amazing = bind(returnFoo, context);var amazing = returnFoo.bind(context);var _toString = Function.prototype.call.bind(Object.prototype.toString);
_toString({}); // "[object Object]"
_toString(window); // "[object Window]"
_toString([]); // "[object Array]"
Object.prototype.toString.call( [] )
var _toString = Object.prototype.toString
_toString.call( [] )
function bind (context, method) {
var prefix = Array.prototype.slice.call(arguments,2);
return function(){
return method.apply(context, prefix.concat(Array.prototype.slice.call(arguments)));
}
}
// Немного надоедает использовать .call каждый раз. Может воспользоваться bind?
// Точно! Давайте привяжем функцию call к контексту slice.
slice = Function.prototype.call.bind(Array.prototype.slice);
// Но мы можем использовать apply и call, они позволяют нам передавать нужный контекст
slice.call([1,2,3], 0, 1); // => [1]
Function.prototype.call(slice, [1,2,3], 0, 1); // => [1]
var foo = {
prop: 0,
bar: function(){
console.log(++this.prop);
},
init: function(){
this.bar = this.bar.bind(this);
document.addEventListener("click", this.bar);
}
};
foo.init();
foo.bar();
init: function(){
var callback = this.bar.bind(this);
document.addEventListener("click", callback);
bar: (function(){
console.log(++this.prop);
}).bind(this),
init: function(){
document.addEventListener("click", this.bar);
}
Bind, Call и Apply в JavaScript