0

I want to create a new array as an attribute of the object once I create a new instance. But I get the following error in Chrome: "Uncaught TypeError: Cannot call method 'push' of undefined". Players seems to be unkown. But why?

function Team(name) {
    this.Name = name;
    this.Players = new Array();
}

Team.prototype.AddPlayer = new function (player) {
    this.Players.push(player); //error
}
1
  • 1
    Within what constructor? Commented Nov 6, 2012 at 17:28

2 Answers 2

2

Just remove the 'new' in this line

Team.prototype.AddPlayer = function (player) {
Sign up to request clarification or add additional context in comments.

Comments

0

Your code is correct, but you need to be sure to make a new Team instance using new.

var t = new Team("foo");
t.AddPlayer("bar");

Oops, one error in your code. Remove new from before function in the .prototype assignment.

function Team(name) {
    this.Name = name;
    this.Players = new Array();
}

Team.prototype.AddPlayer = /*new*/ function (player) {
    this.Players.push(player);
}

Because you had new before the function, you were actually using the anonymous function as a constructor, which means it was being invoked.

To be clear, new does not make a new function unless it is placed before the Function constructor.

2 Comments

The problem is the new keyword on the prototype declaration
Thanks for the explanation. It's the first time I'm working with prototypes and "real" objects in JS.

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.