function test() {
this.list = {};
document.getElementById("test").innerHTML = "";
this.list['test1']= new mutation("test1", 2, {"damage":{"freq":2, "size":"d6"}});
this.list['test2']= new mutation("test2", 1, {"range":"long"});
this.list['test1'].level=5;
alert("test running");
this.addOptions();
}
test.prototype.addOptions = function(){
alert("addOptions Running");
var node = document.getElementById("select");
var strName;
for(strName in this.list) {
var optionNode = document.createElement('option');
var textnode = document.createTextNode(this.list[strName].name);
optionNode.appendChild(textnode);
node.appendChild(optionNode);
document.getElementById("test").appendChild(this.list[strName].display());
}
}
我已经用头撞墙大约一个小时了,但没有效果。
我在另一个文件中做了同样的事情,它不仅有效并且仍然有效,而且实际上是由该文件在mutations()定义中调用的。
我在 this.addOptions()
行上收到 Uncaught“TypeError: undefined is not a function”
错误。在我将其重构为新文件并开始尝试为下一步应用原型(prototype)之前,所有代码都在工作,这将根据“选择”框中的列表进行显示更新。再次,巨大的工作正在进行中,但这相当有效地阻碍了进展。
编辑:这段代码工作得很好
function mutation(nam, freq, opts) {
this.opts=opts;
this.name=nam;
this.nameText = document.createTextNode(nam+": ");
this.frequency=freq;
this.level=0;
this.upd();
}
mutation.prototype.display = function(){
this.upd();
var node=document.createElement('span');
var ret = document.createElement('br');
node.appendChild(this.nameText);
node.appendChild(this.damage);
node.appendChild(this.range);
node.appendChild(ret);
return node;
};
mutation.prototype.upd = function(){
if(this.opts['damage'] || this.opts['Damage']) {
var dmg = calcDamage(this.level, this.opts['damage']['freq'], this.opts['damage']['size']);
this.damage = document.createTextNode(dmg+" ");
} else {
this.damage = document.createTextNode("");
}
if(this.opts['range'] || this.opts['Range']) {
var rng=rangeFunction(this.level,this.opts['range']);
this.range = document.createTextNode(rng+"ft. ");
} else {
this.range = document.createTextNode("");
}
};
最佳答案
如果您调用“test()”而不是“new test()”,您将收到您所描述的错误。如果您忘记了“new”,那么“this”将不会扩展 test.prototype,然后 this.addOptions() 将不存在。使用“new”调用会创建一个“this”,它扩展了原型(prototype)并具有对 addOptions 的引用。
关于Javascript:使用原型(prototype)函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27198434/