我想用一个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类自身的方法?
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类自身的方法?
this.onMouseOver is undefined。
改成
document.addEventListener(this.btn,"mouseover",function(){Button.prototype.onMouseOver.apply(Button,arguments);});
先非常感谢你的回答。
貌似现在this.abc()中的this指向Button了,但是貌似就只是Button对象的空壳,有很多方法名,但是里面什么都没有。
var _this = this;
document.addEventListener(this.btn,"mouseover",function() {_this.onMouseOver()});
因为事件类型
obj.onmouseover = function(){//这里的this指向obj, 所以提前用__this把Button指针给保存起来然后引用}