我宣佈一個新的對象,因爲它遵循:爲什麼在函數中使用這個對象導致Javascript TypeError(undefined)引發?
function node(){
this.tag = null;
this.Tdata = [];
this.Tchilds = [];
}
我想在函數中使用這個對象:
function Check(root /*I want to use root as type node*/) {
for(var i = 0; i < root.Tdata.length; i++){
if(root.Tdata[i] == -1)
arg++;
}
}
的瀏覽器說:TypeError: root.Tdata is undefined
當我聲明一個變量(出功能的範圍)var root = new node();
&我使用root.Tdata[]
一切工作正常。
那麼我該如何在函數中使用這個對象呢?
編輯:
在函數調用我所做的:
var rootExt = new node();
rootExt.Tdata[0] = -1;
rootExt.Tchilds[0] = -1;
Check(rootExt);
你是怎麼調用'Check'函數的?我已經測試了你的代碼,如下所示:'Check(new node());'它按預期工作。 – maddockst
你應該閱讀關於新操作符的文檔.. [這裏](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) – puemos
你應該將對象傳遞給函數,如果我正確地理解了你的問題,請檢查(新節點());' –