我想用一个div做按钮,自编了个Button对象包含一个div对象,如下:window.onload = function(){
   var xxx = new Button("ButtonA",40,40);
   xxx.initial();
}function Button(id, width, height){
this.btn = document.createElement("div");
this.btn.id = id;  
this.btn.style.width = width;
this.btn.style.height = this.height;
document.body.appendChild(this.btn);
}
Button.prototype.Initial = function(){
document.addEventListener(this.btn,"mouseover",this.onMouseOver);
         //将div的onmouseover事件与自制类Button.onMouseOver()绑定.
Button.prototype.onMouseOver = function(){ //回调函数
this.abc(); 
}Button.prototype.abc = function(){
    //
}
结果发现,红色的this是指向btn对象的,不是Button对象。杯具了!
怎样改才可以在这个绑定回调函数调用Button类自身的方法?

解决方案 »

  1.   

    document.addEventListener(this.btn,"mouseover",this.onMouseOver); 这里不就是给Button的btn注册的事件吗,你说在事件处理方法里面的this会指向谁呢?
      

  2.   

    我说的这个this.abc();中的this指向btn,而不是指向Button.
      

  3.   

    这样,我无法调用Button中的abc。 
      

  4.   

    document.addEventListener(this.btn,"mouseover",function(){this.onMouseOver.call(Button);}); 
      

  5.   

    document.addEventListener(this.btn,"mouseover",this.onMouseOver.call(this)); 
      

  6.   

    还是不行,结果是:
    this.onMouseOver is undefined。
      

  7.   


    改成
    document.addEventListener(this.btn,"mouseover",function(){Button.prototype.onMouseOver.apply(Button,arguments);});
      

  8.   


    先非常感谢你的回答。
    貌似现在this.abc()中的this指向Button了,但是貌似就只是Button对象的空壳,有很多方法名,但是里面什么都没有。
      

  9.   

    Button.prototype.Initial = function(){ 
    var _this = this;
    document.addEventListener(this.btn,"mouseover",function() {_this.onMouseOver()}); 
      

  10.   

    我想问需要改arguments成new Button时的填入的参数吗?本人对call()和apply()并不怎么了解。
      

  11.   


    因为事件类型
    obj.onmouseover = function(){//这里的this指向obj, 所以提前用__this把Button指针给保存起来然后引用}