Javascript this关键字问题 本帖最后由 goukili 于 2010-06-26 17:42:48 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 用变量保存 this 的范围 function JSClass() { this._height = 10; th=this; } JSClass.prototype.initialize = function() { alert(this); // 此时this对象是实例对象jc // 此时相当于创建了匿名函数document.onmousedown = function(){ alert(this); alert(this._height);} document.onmousedown = th.doit; }; JSClass.prototype.doit= function() { alert(this); // 此时this对象是document对象 alert(th._height); // document对象是不存在_height属性的,所以显示undefined }; var jc = new JSClass(); jc.initialize(); to daxuejianku:用变量保存this能运行, 不过我有个问题,此处th变量是全局的,很容易造成冲突,例如如果有其他的类使用了同样的变量名就要出问题了 我觉得这样保存this只是表面上解决了问题,new一个实例对象还好,如果是new多个,那么所有的实例对象都重复对th赋值保存this,一定会出现问题的,没有其他更好的方法嘛? var _this = this; document.onmousedown = function() { _this.doit(); } function JSClass() { this._height = 10; } JSClass.prototype.initialize = function() { alert(this); var jsclass = this; alert(jsclass._height);//output 10 document.onmousedown = function(){ jsclass.doit(); }; }; JSClass.prototype.doit= function() { alert(this); // 此时this对象是document对象 alert(this._height); // document对象是不存在_height属性的,所以显示undefined }; var jc = new JSClass(); jc.initialize(); javascript求解bug JS构造函数问题 关于JS动态传递参数的问题~ 请教使用obj.setCapture(window.captureEvents)的好处 求教: 鼠标单击单元格变色 分不够再加 务求大家帮助! 工作流中 设计 计算控件 的一个问题 mozilla下如何判断用户按键的码值 问个关于删除确认的很简单问题 Javascript可以读写文件吗 关闭父画面时,可否控制将所有的子画面也都关闭? qq在线客服位置问题求救!!! ext grid 的根据前一项 后一项相应的值发生改变咋写?
{
this._height = 10;
th=this;
}
JSClass.prototype.initialize = function()
{
alert(this); // 此时this对象是实例对象jc
// 此时相当于创建了匿名函数document.onmousedown = function(){ alert(this); alert(this._height);}
document.onmousedown = th.doit;
}; JSClass.prototype.doit= function()
{
alert(this); // 此时this对象是document对象
alert(th._height); // document对象是不存在_height属性的,所以显示undefined
}; var jc = new JSClass();
jc.initialize();
var _this = this;
document.onmousedown = function()
{
_this.doit();
}
{
this._height = 10;
}
JSClass.prototype.initialize = function()
{
alert(this);
var jsclass = this;
alert(jsclass._height);//output 10
document.onmousedown = function(){
jsclass.doit();
};
}; JSClass.prototype.doit= function()
{
alert(this); // 此时this对象是document对象
alert(this._height); // document对象是不存在_height属性的,所以显示undefined
}; var jc = new JSClass();
jc.initialize();