我们大家都知道,javascript中this的指向会经常的发生改变,通常我们会进行
var that=this,然后在进行调用,最近一段时间经常写react的时候会使用
class Example2 extends React.Component {
contructor() {
super();
this.handle = this.handle.bind(this);
}
这样的es6写法来绑定this,一直没有追究其bind的的实现!后来发现了javascript语言精粹中的bind写法
Function.method('bind',function (that){
//返回一个函数,调用这个函数就像调用那个对象的一个方法
var method = this,
slice = Array.prototype.slice,args=slice.apply(arguments,[1]);
return function (){
return method.apply(that,args.concat(slice.apply(arguments,[0])))
}
})
var x=function (){
return this.value
}.bind({value:666});
alert(x()) //666