javascript - Array in Node.js, how to work with it -
i'm newbye in web programming , more in javascript, i'm trying learn learn node.js, , found strange error... i've got code:
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); (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();
i've got problem here... may see, _childelements
intended array, , i've got function addchild
should add child element it.
the rest of code works, gives me following error:
c:\zerok\devcenter\structify\public_html\js\object.js:22 structobject._childelements.push(element); ^ typeerror: cannot read property 'push' of undefined
why childelements not defined? tried not defining variable, , tried equaling this._childelements = [];
none of these ways seem work either.
what should can work dynamically array?
structobject._childelements.push(element);
you're trying modify (non-existent) _childelements
property of constructor function instead of instance created new structobject
.
use this
instead of structobject
on line.
it conventional, in javascript, use variables starting capital letters constructor functions.
var structobject = function(...) {
would better written as:
var structobject = function(...) {
or (since constructor makes objects):
var struct = function(...) {
or (because named functions easier deal in debuggers):
function struct (...) {
Comments
Post a Comment