我正在开发一个以姓名和年龄作为参数的 Person 构造函数,并尝试实现一种检索所有“Person”实例当前年龄值并输出平均值的方法。这是我的代码...
var Person = (function() {
//private state
var inst = 1;
function Person(name, age) {
this.name = name;
this.age = age;
Object.defineProperty(this, "age", {
get: function() {
return age;
},
set: function(num) {
age = num;
}
});
Object.defineProperty(this, "_id", {
value: inst++
});
}
//Attempt to return number of instances divided by all current Person weights
Person.prototype.aveAge = function() {
return inst;
};
return Person;
}());
var jim = new Person("jim", 32);
var richard = new Person("richard", 27);
richard.age = 28;
var alfie = new Person("alfie", 42);
Person.aveAge() //Returns TypeError: Person.aveAge is not a function
我设置了一个在所有实例 (inst) 之间共享的变量,每次创建另一个实例时该变量都会递增并分配一个唯一的 ID。我无法弄清楚如何使用我在底部添加的 aveAge 原型(prototype)来获取现有的所有 Person 实例的每个“年龄”值。当我尝试调用它来测试变量“inst”是否包含正确的实例数时,我还收到“TypeError:Person.aveAge 不是函数”。有人知道我哪里出错了吗?
最佳答案
当提到人的时候,对一个人进行年龄统计感觉很奇怪。请注意,将内容卡在 __proto__
上使它们可以从构造函数 (Person) 中使用,而将内容卡在 prototype
上使它们可以从实例 (richard) 中可用。如果更新年龄,则需要通过 setAge 完成,以便 PeopleTracker 知道更新其内存。另外,在我的示例中,平均值仅在需要时计算,而不是每次人们想知道是什么时计算。
var peopleTracker = {
_count: 0,
_ages: [],
averageAge: 0,
addPerson: function (age) {
var pt = peopleTracker;
pt._count += 1;
pt._ages.push(age);
pt.getAverage();
},
getAverage: function () {
var sum = 0,
pt = peopleTracker;
sum = pt._ages.reduce(function (a, b) {
return a + b;
});
pt.averageAge = Math.round(sum / pt._count);
},
update: function (oldAge, newAge) {
var pt = peopleTracker,
ages = pt._ages,
i = ages.indexOf(oldAge);
ages.splice(i, 1, newAge);
pt.getAverage();
}
};
var Person = function (name, age) {
this.name = name;
this.age = age;
peopleTracker.addPerson(age);
};
Person.__proto__ = { // available from the constructor
Constructor: Person,
setAge: function (age) {
var oldAge = this.age;
this.age = age;
peopleTracker.update(oldAge, age);
},
aveAge: function () {
return peopleTracker.averageAge;
}
};
Person.prototype = Person.__proto__; // now also available from the instance
var jim = new Person("Jim", 32),
richard = new Person("Richard", 27),
alfie = new Person("Alfie", 42);
Person.aveAge(); // 34
richard.aveAge(); // 34
richard.setAge(20);
Person.aveAge(); // 31
richard.aveAge(); // 31
关于javascript - 检索对象的所有实例中保存的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324216/