[英]Javascript: Issue using prototype functions
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"
。 在我將其重構為新文件並開始嘗試將原型應用於下一步(即根據“選擇”框中的列表進行顯示更新)之前,所有代碼均在工作。 同樣,大量工作仍在進行中,但這相當有效地阻止了進展。
編輯:此代碼工作正常
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()構造函數,並且其定義被“提升”,即移至代碼的頂部。 因此,構造函數(test())可以正常工作,但原型方法仍未定義。 但是,目前仍未定義分配給原型的第二部分。 請檢查您的代碼順序。
另一個有錯誤的例子:
a = new A(); // created OK
a.foo(); // error: foo is not a function
A = function() {};
A.prototype.foo = function() { return 'bar'; }
而這一作品:
A = function() {};
A.prototype.foo = function() { return 'bar'; }
a = new A(); // created OK
a.foo(); // returns 'bar'
如果調用“ test()”而不是“ new test()”,則會得到描述的錯誤。 如果您忘記了“新”,那么“ this”將不會擴展test.prototype,那么this.addOptions()將不存在。 用'new'調用會創建一個'this',它擴展了原型並引用了addOptions。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.