简体   繁体   English

如何在构造函数中创建数组?

[英]How to create an array within the constructor?

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". 但是我在Chrome中遇到以下错误:“未捕获的TypeError:无法调用未定义的方法'push'”。 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
}

只需删除此行中的“新”即可

Team.prototype.AddPlayer = function (player) {

Your code is correct, but you need to be sure to make a new Team instance using new . 您的代码是正确的,但您需要确保使用new创建一个新的Team实例。

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

Oops, one error in your code. 糟糕,您的代码中有一个错误。 Remove new from before function in the .prototype assignment. 删除new从之前function.prototype分配。

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 . 因为你在函数之前有了new的,所以你实际上是使用匿名函数作为构造函数 ,这意味着它正在被调用

To be clear, new does not make a new function unless it is placed before the Function constructor. 要清楚, new 不会创建新函数,除非它放在Function构造Function之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM