0
我想学习如何在JavaScript中使用原型,我希望有人能向我解释以下内容。如何使用原型?
可以说,我有一个原型看起来像这样一个对象:
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)。我将如何做到这一点?
迭代阵列之上并调用'这些对象的方法add'? –
'numbers [i] .add()'? – Oriol
如果你想了解更多关于“原型”的内容,我建议阅读[你不知道JS-原型](https://github.com/getify/You-Dont-Know-JS/blob/主/这个%20&%20object%20prototypes/ch5.md)。您也可以在MDN上找到有用的文章:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain,https://developer.mozilla.org/en-US/docs/Web/ JavaScript/Guide/Details_of_the_Object_Model –