[英]Array in Node.js, how to work with it
我是Web編程的再見者,而Javascript則更多。但是,我在學習Node.js的同時嘗試學習它,但是我發現了這個奇怪的錯誤……我得到了以下代碼:
var structobject = function(type, title, isReplicable, isVisible) {
this._type = type;
this._title = title;
this._childElements = new Array();
this._isReplicable = isReplicable;
this._id = 0; //TODO
};
structobject.prototype.addChild = function (element) {
structobject._childElements.push(element);
};
structobject.prototype.stringify = function () {
console.log("Main element: "+this._title);
for (var i=0;i<this._childElements.length;i++) {
console.log("Child "+i+": "+this._childElements[i]._title);
}
};
structo1 = new structobject(1, "element1", true, true);
structo1.addChild(new structobject(2, "element2", true, true));
structo1.stringify();
我在這里遇到了一個問題...正如您可能會看到的, _childElements
原本是一個數組,並且我有addchild
函數,該函數應該在其中添加一個子元素。
其余代碼可以正常工作,但這給了我以下錯誤:
C:\Zerok\DevCenter\Structify\public_html\js\object.js:22
structobject._childElements.push(element);
^
TypeError: Cannot read property 'push' of undefined
為什么說未定義childElements? 我嘗試不定義變量,也嘗試將其等於this._childElements = [];
但這些方法似乎都不起作用。
我應該怎么做才能使該陣列動態工作?
structobject._childElements.push(element);
您正在嘗試修改Constructor函數的(不存在的) _childElements
屬性,而不是使用new structobject
創建的實例 。
在該行上使用this
代替structobject
。
在JavaScript中,通常使用以大寫字母開頭的變量作為構造函數。
var structobject = function(...) {
最好寫成:
var Structobject = function(...) {
或(因為它是制造對象的構造函數):
var Struct = function(...) {
或(因為命名函數更容易在調試器中處理):
function Struct (...) {
用它代替structobject
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.