ECMAScript5(ES5)中bind方法使用小结
一直以来对和this有关的东西模糊不清,譬如call、apply等等。这次看到一个和bind有关的笔试题,故记此文以备忘。
bind和call以及apply一样,都是可以改变上下文的this指向的。不同的是,call和apply一样,直接引用在方法上,而bind绑定this后返回一个方法,但内部核心还是apply。
直接看例子:
varobj={
a:1,
b:2,
getCount:function(c,d){
returnthis.a+this.b+c+d;
}
};
window.a=window.b=0;
console.log(obj.getCount(3,4)); //10
varfunc=obj.getCount;
console.log(func(3,4)); //7
为何会这样?因为func在上下文中的this是window!bind的存在正是为了改变this指向获取想要的值:
varobj={
a:1,
b:2,
getCount:function(c,d){
returnthis.a+this.b+c+d;
}
};
window.a=window.b=0;
varfunc=obj.getCount.bind(obj);
console.log(func(3,4)); //10
bind是function的一个函数扩展方法,bind以后代码重新绑定了func内部的this指向(obj),但是不兼容ie6~8,兼容代码如下:
varobj={
a:1,
b:2,
getCount:function(c,d){
returnthis.a+this.b+c+d;
}
};
Function.prototype.bind=Function.prototype.bind||function(context){
varthat=this;
returnfunction(){
//console.log(arguments);//console[3,4]ifie<6-8>
returnthat.apply(context,arguments);
}
}
window.a=window.b=0;
varfunc=obj.getCount.bind(obj);
console.log(func(3,4)); //10
其实在我看来bind的核心是返回一个未执行的方法,如果直接使用apply或者call:
varans=obj.getCount.apply(obj,[3,4]); console.log(ans);//10
无法使用简写的func函数构造,所以用bind传递this指向,再返回一个未执行的方法,实现方式相当巧妙。
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短