关于javascript对象构造函数的问题

来源:百度知道 编辑:UC知道 时间:2024/07/05 04:17:49
function createObj(){
this = document.createElement("A");
this.href = "http://www.baidu.com";
this.innerHTML = "百度";
document.body.appendChild(this);
}
var baidu = new createObj()

运行后,发现不能成立.分析了下原因
好像是this这个对象不能等于document.createElement("A");
怎么使其成立,请教各位高手....

this 是javascript 保留字,不能作为变量使用
而且构造函数里面的 this是指代var var baidu = new createObj() 中的百度
要实现你的功能,
function createObj(urlPath,innerStr){
this.href = urlPath
this.innHTML = innerStr
}
createObj.prototype.createHTML=function(){
var a = document.createElement("A");
a.href = this.href
a.innerHTML = this.innHTML
document.body.appendChild(a);
}
var baidu = new createObj("http://www.baidu.com","百度")
baidu.createHTML()