如下代码, errorRemove()
方法中 this 指向的是 defaults.ID
,然而我在 init()
中对 errorRemove()
方法进行了事件绑定,这时 this
的指向,发生了改变,成了 defaults.ID
;
如何在继续使用 this
而不使用其他办法的情况下,做到 this
的指向经过事件绑定后不发生改变
(function(){
//默认配置
var defaults = {
ID : $('#userName'),
Error : $('.error'),
userBooleans : false
};
var userBasic = function(options){
this.config = $.extend({}, defaults, options);
this.init();
};
userBasic.prototype = {
init : function(){
var that = this;
//这里 errorRemove 中的 this 指向的是 defaults.ID
this.config.ID.bind('focus',that.errorRemove);
},
errorRemove : function(txt){
//这里 this 指向的是 defaults.Error
this.config.Error.html(txt);
this.config.userBooleans = false;
}
}
});
什么叫“this指向的是 defaults.ID ... this 发生了改变,成了 defaults.ID”
不知道你要说明的问题,告诉你个函数吧 bind (不是jq的bind,是js原生的bind)
http://zonxin.github.io/post/2015/11/jav...