Javascript通过bind()掌控this
function ReplaceProcessor() {
this._dom = {
btnReplace : $('#ro_btnReplace'),
btnComplete: $('#ro_btnComplete')
};
// Bind events
this._dom.btnReplace.on('click', this._onReplace.bind(this));
this._dom.btnComplete.on('click', this._onComplete.bind(this));
}
ReplaceProcessor.prototype._onReplace = function(){
// code
this._dom.btnComplete.html("OK");
}
先上官网的解释,不管我们个人的解释是多么的接地气,官方API到底还是比较靠谱的:bind方法会创建一个新函数,称为绑定函数.当调用这个绑定函数时,绑定函数会以创建它时传入bind方法的第一个参数作为this,传入bind方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数.
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis ? this : oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};}
如何,这就是我之前说的,本来通常情况下处理函数都要用一层匿名函数包裹一下,才能维持处理函数本身的this.这里直接通过.bind(logger)人为的将其执行时的this指向logger对象。var logger = {
x: 0,
updateCount: function(){
this.x++;
console.log(this.x);
}
}
// 下面两段代码的实现是一样的
document.querySelector('button').addEventListener('click', function(){
logger.updateCount();
});
document.querySelector('button').addEventListener('click', logger.updateCount.bind(logger));
(二)setTimeout.bind()创建了一个函数,当这个函数在被调用的时候,它的 this 关键词会被设置成被传入的值(这里指调用bind()时传入的参数)。
function LateBloomer() {
this.petalCount = Math.ceil( Math.random() * 12 ) + 1;
}
// declare bloom after a delay of 1 second
LateBloomer.prototype.bloom = function() {
window.setTimeout( this.declare.bind( this ), 1000 );
};
LateBloomer.prototype.declare = function() {
console.log('I am a beautiful flower with ' + this.petalCount + ' petals!');
};
//设立一个简单地对象作为“上下文”
var context = { foo: "bar" };
//一个在this上下文中指向foo变量的函数
function returnFoo () {
return this.foo;
}
// 变量在作用域中不存在,因此显示undefined
returnFoo(); // => undefined
// 如果我们把它绑定在context上下文中
var bound = returnFoo.bind(context);
// 现在的作用域中有这个变量了
bound(); // => "bar"
//
// 这就是Function.prototype.bind的作用.
//由于returnFoo也是函数,因此它继承了function的原型
//
// 如果你觉得享受,接着往下读,下面更精彩
//
// 有许多方法将函数绑定在一个上下文中
// Call和Apply让你能在上下文中调用函数
returnFoo.call(context); // => bar
returnFoo.apply(context); // => bar
// 将函数添加到对象中
context.returnFoo = returnFoo;
context.returnFoo(); // => bar
//
// 现在我们来玩一点诡异的东西
//
// Array.prototype 中有一个叫做slice的方法
// 对一个数组调用slice,可以返回一个从start index到end index的数组
[1,2,3].slice(0,1); // => [1]
// 因此我们把Array.slice赋值给一个本地变量slice
var slice = Array.prototype.slice;
//现在的slice是"自由的",由于Array.prototype中的slice一般指定了上下文
//或者默认为this,此时slice将不起作用
slice(0, 1); // => TypeError: can't convert undefined to object
slice([1,2,3], 0, 1); // => TypeError: ...
// 但是如果我们使用call或者apply,slice又将在一个上下文中执行
slice.call([1,2,3], 0, 1); // => [1]
// Apply和Call差不多,知识参数要放在一个数组中
slice.apply([1,2,3], [0,1]); // => [1]
// 使用call没错了,那么能不呢使用bind呢?
// 没错,我们来把"call"绑定在slice上
slice = Function.prototype.call.bind(Array.prototype.slice);
// 现在slice可以把第一个参数作为上下文了
slice([1,2,3], 0, 1); // => [1]
//
// 很酷,对吧。现在再来完成一件事
//
// 现在我们对bind本身做一件刚才对silce做的事
var bind = Function.prototype.call.bind(Function.prototype.bind);
// 在这里总结一下,好好想想
// 发生了什么事? 我们改变了call,
// 返回一个接收一个函数和一个上下文作为ic桉树的函数
//并且返回了一个完全绑定的函数
// 回到最初的例子
var context = { foo: "bar" };
function returnFoo () {
return this.foo;
}
// 现在来使用神奇的"bind"函数
var amazing = bind(returnFoo, context);
amazing(); // => bar
OK,感觉说到这里bind是做什么的应该么可以理解了,最近打算写写如何在没有MVC的库的状态下,写出带有MVC思想的代码~GO.$.ajax({
url: url,
type: 'post',
dataType: 'json',
data: {'info': info}
})
.done((function(data) {
if(data.status){
// 这里this指向的是外层bind进来的this
this._data.process_type = info.process_type;
}else{
uUnique.noticeBox.showWarning(data.message);
}
}).bind(this));