JavaScript 比较头疼的问题.

[code="javascript"]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



无标题文档 var obj = new Object(); obj.load = function(){ this.url = "我是URL的值"; this.showBtn(); } obj.load.prototype = { getUrl:function(){ alert(this.url); }, showBtn:function(){ var btn = document.createElement("input"); btn.type = "button"; btn.value = "demo"; document.body.appendChild(btn); //这个按钮点击的时候,我想能访问到 "我是URL的值这句话" btn.onclick = this.getUrl; } } window.onload = function(){ new obj.load(); }





[/code]
[b]问题补充:[/b]
我也想到了这个解法,真的就没有其他的办法让事件的scope跳回原来的对象么?

this总在变化之中,因为js的对象是在变化之中的,所以要一个确定的this限制了语言的能力,如果想要一直用同一个this作为对本对象的引用,可以这样:

obj.load.prototype = {

getUrl:function(){

alert(thisObj.url);

},

showBtn:function(){

var btn = document.createElement("input");

btn.type = "button";

btn.value = "demo";

document.body.appendChild(btn);

//这个按钮点击的时候,我想能访问到 "我是URL的值这句话"

thisObj = this;
btn.onclick = this.getUrl;

}

}

因为当你点击按钮的时候scope已经变化了,这是的this变成了input而不是window下的new obj.load()

对了,这个问题可以用闭包来解决:

    //这个按钮点击的时候,我想能访问到 "我是URL的值这句话"   
var v = this.url;
btn.onclick = function(){
    alert(v);
}

this是指当前作用域,当你创建一个按钮并激活它的时候,作用域this就会发生转移,这个时候,你当前的this就不起作用了,你可以这样来避免发生这样的事情
创建按钮的时候在外部创建,不要在方法里面创建,当然也可以采用闭包的方式,万一不行你就把作用域转移回来
obj.load.prototype = {
getUrl:function(){

alert(thisObj.url);

},

showBtn:function(){

var btn = document.createElement("input");

btn.type = "button";

btn.value = "demo";

document.body.appendChild(btn);

//这个按钮点击的时候,我想能访问到 "我是URL的值这句话"

thisObj = this;
btn.onclick = this.getUrl;

}

}
楼上的这个可行