Reputation: 1503
I'm a newbye in web programming and even more in Javascript, but I'm trying to learn it as I learn Node.js, and I found this strange error... I've got this 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);
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();
I've got a problem here... as you may see, _childElements
is intended to be an array, and I've got the function addchild
which should add a child element into it.
The rest of the code works, but this gives me the following error:
C:\Zerok\DevCenter\Structify\public_html\js\object.js:22
structobject._childElements.push(element);
^
TypeError: Cannot read property 'push' of undefined
Why does it say childElements is not defined? I tried not defining the variable, and also tried equaling it to this._childElements = [];
but none of these ways seem to work either.
What should I do so I can work dynamically with this array?
Upvotes: 1
Views: 108
Reputation: 943185
structobject._childElements.push(element);
You're trying to modify the (non-existent) _childElements
property of the Constructor function instead of the instance you created with new structobject
.
Use this
instead of structobject
on that line.
It is conventional, in JavaScript, to use variables starting with capital letters for constructor functions.
var structobject = function(...) {
would be better written as:
var Structobject = function(...) {
or (since it is a constructor that makes objects):
var Struct = function(...) {
or (because named functions are easier to deal with in debuggers):
function Struct (...) {
Upvotes: 5