我对JS还是很陌生,我想把头围绕在JS中的对象主题上。我想做的是将对象原型的属性设置为未初始化的数组,以便以后可以向该数组添加多个对象(对于原型对象的实例)到目前为止,我的代码如下所示:
function cocktail(){
this.prototype.ingredients = [];
this.printIngredients = function() {
var i;
for (i = 0; i<this.ingredients.length; ++i) {
console.log(this.ingredients.fluid);
console.log(this.ingredients.amount);
}
}
}
var Mojito = new cocktail();
Mojito.ingredients.push({"fluid":"White Rum", "amount":0.05});
Mojito.printIngredients();
抛出:
TypeError:无法设置未定义的属性“成分”
如果我将代码更改为:
this.ingredients = [];
它可以工作,但是printIngredients()方法会打印两次未定义的内容。当我做:
var array = [];
array.push({"a":1, "b":2});
console.log(array[0].a, array[0].b)
一切都按我预期的那样工作。有人可以澄清我做错了什么,以及我的想法错综复杂的地方吗?
将您的代码更改为
function cocktail(){
this.ingredients = []; //this doesn't have prototype property
this.printIngredients = function() {
var i;
for (i = 0; i<this.ingredients.length; ++i) {
console.log(this.ingredients[i].fluid);//use the counter variable to get the fluid value at current counter value
console.log(this.ingredients[i].amount);//use the counter variable to get the amount value at current counter value
}
}
}
var Mojito = new cocktail();
console.log(Mojito.ingredients)
Mojito.ingredients.push({"fluid":"White Rum", "amount":0.05});
Mojito.printIngredients();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句