我现在所认识到的最主要的应用场景是在构造函数里面,会出现this指向不一致的情况,特别是当构造函数里面的方法需要绑定事件时,比如下下面这个例子:
LightEntire.prototype.bindEvent = function(){
this.$el.on('mouseover','.rating-item',function(){
this.lightOn($item,$(this).index() + 1);
})
}
这里面的lightOn函数我们本来是想希望它指向LightEntire这个构造函数的执行对象的,但是在这里却指向了this.$el,那怎么办呢?
有两种方法,一种是在On绑定事件外面把this的指向给保留下来,就像这样:
LightEntire.prototype.bindEvent = function(){
var that = this;//我们用that在绑定事件外面把this指向给保留下来
this.$el.on('mouseover','.rating-item',function(){
this.lightOn($item,$(this).index() + 1);
})
}
另外一种是用proxy函数
LightEntire.prototype.bindEvent = function(){
this.$el.on('mouseover','.rating-item',proxy(function(){
this.lightOn($item,$(this).index() + 1);
},this))
}
proxy(执行的函数,目的对象)