我刚刚开始考虑关闭。拥有私有(private)变量和私有(private)方法。我遇到的问题是调用方法时,开发人员控制台告诉我“未定义不是函数”。
Javascript:
var shop = (function() {
var items = [];
return {
Item: function(data) {
this.id = data[0];
this.item = data[1];
this.description = data[2];
this.price = data[3];
this.count = data[4];
},
addItem: function(id, item, description, price) {
items.push(this.Item(id, item, description, price));
},
print: function() {
var itemCon = document.getElementById('items'),
html = "";
items.forEach(function(item) {
html += '<div class="item">';
for(prop in item) {
if(prop != "id") {
if(prop != "count") {
if(prop === "price") {
html += '<p><span class="title">' + prop + '</span>: £' + item[prop] + '</p>';
} else {
html += '<p><span class="title">' + prop + '</span>: ' + item[prop] + '</p>';
};
};
};
};
html += '<button class="addButton" data-id="' + item.id + '">Add to Basket</button>'
html += '</div>';
});
itemCon.innerHTML += html;
}
};
});
function init() {
shop.addItem("0", "coat", "Warm yes!", 24.99);
shop.print;
};
window.onload = init;
最佳答案
您没有调用 IIFE,因此它没有返回您想要的对象。
var shop = (function() {
var items = [];
return {
// your code
};
})(); // <-- Invoke it!
按照您的方式,您只是将匿名函数分配给 shop
变量,并且该函数对象没有 addItem()
方法。
关于javascript - 无法在闭包中运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27176616/