[英]why am I getting “is not a function error” for my object method?
我收到以下代码的“不是函数”错误
function menu_item(name,price,description,type){
this.name=name;
this.price="$"+price;
this.description=description;
this.type=type;
this.create_item=create_item;
function create_item(){
var item_slot=document.createElement('div');
item_slot.className='item';
item_slot.id=this.name;
document.getElementById(this.type).appendChild(item_slot);
var the_name=document.createTextNode(this.name);
item_slot.appendChild(the_name);
}
}
var hamburger=new menu_item("Hamburger",4.55,"A 6oz patty burger served on your choice of wheat, white, or rye bun.","burger");
var cheeseburger=new menu_item("Cheeseburger",4.95,"A 6oz patty burger served with American,Mozzarella, or Provolone cheese on your choice of wheat, white, or rye bun.","burger");
var bacon_hamburger=new menu_item("Bacon Hamburger",5.65,"A 6oz patty burger and honey glazed bacon served on your choice of wheat, white, or rye bun.","burger");
var bacon_cheeseburger=new menu_item("Hamburger",5.90,"A 6oz patty burger,topped with honey glazed bacon served with American,Mozzarella, or Provolone cheese on your choice of wheat, white, or rye bun.","burger");
//wings
var chicken_wings=new menu_item("Chicken Wings(6)",4.55,"A basket of 6 crispy chicken wings in your choice of bbq,hot,mild, or tangy sauce.","wings");
//fries
var fries=new menu_item("Freedom Fries",1.50,"A 1/2 pound of crispy golden fries.","fries");
var gravy_fries=new menu_item("Gravy Fries",2.50,"A 1/2 pound of freedom fries slathered in gravy and melted cheese.","fries");
//desert
var cheesecake=new menu_item("Cheese Cake",2.00,"Top off you meal with a slice of our signature cheese cake","desert");
var oreocake=new menu_item("Oreo Cake",2.00,"A delectable oreo cheese cake complements any meal well","desert");
var chocolatechip_cookies=new menu_item("Chocolate Chip Cookies",1.50,"A bag of five chocolate chip cookies are always a favorite with the kids.","desert");
//drinks
var drinks=new menu_item("Drinks", 1.00, "16 oz drink of your choice of apple,grape,lemon, or orange soda","drinks");
//various objects created that are then put into array below vv
var food_array=[hamburger,cheeseburger,bacon_cheeseburger,bacon_hamburger,chicken_wings,fries,gravy_fries,cheesecake,oreocake,chocolatechip_cookies,drinks];
function populate_menu(){
for(var x in food_array){
x.create_item();
}
}
然后在HTML中onload执行populate_menu函数,但出现错误...有人能解释为什么会这样吗?
一个问题是, for(var x in obj)
迭代在所有枚举的属性 obj
( 未定义顺序 )。 因此,for-in 不适合将数组作为项目序列进行迭代。
我怀疑代码正在遇到此问题,并找到了一个没有“ create_item”方法的“ non menu_item”对象; 相反,使用如下循环来迭代数组:
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
// ..
}
或者,或者使用ES5中的Array.prototype.forEach :
arr.forEach(function (item) {
// ..
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.