2

I have a JavaScript class defined as shown here:

function Item() { 
  this.init(); 
} 

Item.prototype = { 
  id: null, 
  name: '', 
  description: '', 
  init: function () { 
    this.id = "1"; 
  } 
};

I want to add a property called "logs". I want this property to be an array of other class entities. How do I define this kind of array as a property on my Item class? How do I add entities to that array? Originally, I thought I could add "this.logs = {};" in my init function. Then in my code elsewhere, I tried the following:

Item i = new Item();
i.logs.push(NewLog());

However, the push function through an error that says: "Cannot call method 'push' of undefined"

What am I doing wrong?

2 Answers 2

2

logs is not initialized yet. Add it in the constructor (not to the prototype, because the array would then be shared by all instances of Item):

function Item() { 
  this.init();
  this.logs = []; // Not {}:   [] is equivalent to new Array(), and
}                 //           {} is equivalent to new Object() (not an array)

Also, JavaScript != Java.

var i = new Item() // instead of Item i = new Item();
Sign up to request clarification or add additional context in comments.

2 Comments

How do I add items to the array then? Once "i" is created, how do I "push" items onto the array?
@JQueryMobile You said that you wanted to add elements to the logs array (which is a property of the "class instance"). Use i.logs.push(NewLog());.
0

You can try:

Item.prototype = { 
  id: null, 
  name: '', 
  description: '', 
  init: function () { 
    this.id = "1"; 
  },
  push: Array.prototype.push 
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.