prototype 方法中用 this 指向变量,在使用 bind 绑定事件后 this指向出错

如下代码, 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;
        }
   }
});
阅读 2.1k
1 个回答

什么叫“this指向的是 defaults.ID ... this 发生了改变,成了 defaults.ID”

不知道你要说明的问题,告诉你个函数吧 bind (不是jq的bind,是js原生的bind)
http://zonxin.github.io/post/2015/11/jav...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题