javascript 在function 里return 重写function 而得到更多的作用域 闭包

标题写的有点难理解

问题是

function Obj (){

    this.id = 123;

  this.ele = document.getElementById('big_map_a');

    this.attachEvents();

}

Obj.prototype = {

    attachEvents: function(){

      this.ele.onclick = this.handleClick;

    },

    handleClick: function(){

    //    

    }

}

在上面的代码中   handleClick内部的this变量将被指向 onclick的元素   big_map_a 元素,  无法再使用this来引用Obj类本身,   

而我在handleClick中即要用到big_map_a 又要用到  Obj类的属性方法  

怎么办呢?    this变量指向 事件元素本身是变不了的,只能去想把类的引用通过闭包传进去

function Obj (){

    this.id = 123;

  this.ele = document.getElementById('big_map_a');

    this.attachEvents();

}

Obj.prototype = {

    attachEvents: function(){

         var that = this;

      this.ele.onclick = function(){

       return that.func(this,that);

         };

    },

    handleClick: function(e,o){

    //    

  alert(e.id);  //big_map_a

  alert(o.id);   //123

    }

}

原文地址:https://www.cnblogs.com/yushunwu/p/2173285.html