在页面中用function模拟封装了一个类:

function MyClass()
{
this.Attr1 = null;
this.Button = null;


this.AttachEvent = function()
{
this.Button.onclick = this.ButtonClickHandler;
}

this.ButtonClickHandler = function()
{
this.Attr1 = this.Button.value;
}
} 看上去这段代码没什么问题,但实际运行到button的click事件时,是得不到this.Button或者this.Attr1的,因为此时this是触发事件的对象,即这个button,而不是MyClass这个function.
解决问题的方法是在MyClass构造时伪造一个me对象指向function自已:

function MyClass()
{
var me = this;
this.Attr1 = null;
this.Button = null;


this.AttachEvent = function()
{
me.Button.onclick = me.ButtonClickHandler;
}

this.ButtonClickHandler = function()
{
me.Attr1 = me.Button.value;
}


function MyClass()
{
this.Attr1 = null;
this.Button = null;

this.AttachEvent = function()
{
this.Button.onclick = this.ButtonClickHandler;
}
this.ButtonClickHandler = function()
{
this.Attr1 = this.Button.value;
}
}解决问题的方法是在MyClass构造时伪造一个me对象指向function自已:

function MyClass()
{
var me = this;
this.Attr1 = null;
this.Button = null;

this.AttachEvent = function()
{
me.Button.onclick = me.ButtonClickHandler;
}
this.ButtonClickHandler = function()
{
me.Attr1 = me.Button.value;
}
