我正在学习如何在javascript中使用prototype,我希望有人能给我解释一下。
假设我有一个对象,其原型如下所示:
function Calc(sumOne, sumTwo) {
this.sumOne = sumOne;
this.sumTwo = sumTwo;
}
Calc.prototype.add = function() {
var sum = this.sumOne + this.sumTwo;
return sum;
}然后假设这些对象被存储在一个数组中,当它们像这样被创建时。
var numbers = [];
numbers.push(new Calc(1, 2));
numbers.push(new Calc(3, 4));
numbers.push(new Calc(5, 6));这将产生如下所示的数组
numbers = [{sumOne: 1, sumTwo: 2}, {sumOne: 3, sumTwo: 4}, {sumOne: 5, sumTwo: 6}];如果我现在想在这些对象上运行原型以获得结果(3,7和11)。我该怎么做呢?
发布于 2015-10-21 03:40:28
对于数组中的每个Calc实例,对其调用.add()。
numbers.map(function(calc) {
return calc.add();
});发布于 2015-10-21 03:40:40
迭代它们并调用prototype方法
function Calc(sumOne, sumTwo) {
this.sumOne = sumOne;
this.sumTwo = sumTwo;
}
Calc.prototype.add = function() {
var sum = this.sumOne + this.sumTwo;
return sum;
}
var numbers = [];
numbers.push(new Calc(1, 2));
numbers.push(new Calc(3, 4));
numbers.push(new Calc(5, 6));
numbers.forEach(function(calcObject, index) {
numbers[index] = calcObject.add();
});
console.log(numbers)
https://stackoverflow.com/questions/33245382
复制相似问题