Node.js中的数组,如何使用它
我是networking编程的一个新手,甚至更多的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没有定义? 我试图不定义variables,也试图等于this._childElements = [];
但是这些方式都没有效果。
我该怎么做,所以我可以dynamic使用这个数组?
structobject._childElements.push(element);
您正在尝试修改构造函数的(不存在的) _childElements
属性,而不是使用new structobject
创build的实例 。
在这一行使用this
而不是structobject
。
在JavaScript中,使用以大写字母开头的variables作为构造函数是常规的。
var structobject = function(...) {
最好写成:
var Structobject = function(...) {
或(因为它是一个构造函数,使对象):
var Struct = function(...) {
或者(因为命名函数在debugging器中更容易处理):
function Struct (...) {
使用这个而不是structobject