在Javascript OOP中创建函数

在Javascript OOP中创建函数,javascript,oop,Javascript,Oop,将函数列表转换为顺序,使其成为OOP。 目前我有一个类shoppingCart功能。 在我们的购物车里;保存、加载、删除等,然后访问它 a) 这是用OOP编写的吗 b) 如何访问特定功能 JS var cart = []; function shoppingCart() { //var Item = function(title, description, price, image_url, count) { this.newitem = function(title, descri

将函数列表转换为顺序,使其成为OOP。 目前我有一个类shoppingCart功能。 在我们的购物车里;保存、加载、删除等,然后访问它

a) 这是用OOP编写的吗 b) 如何访问特定功能

JS

var cart = [];

function shoppingCart() {
  //var Item = function(title, description, price, image_url, count) { 
  this.newitem = function(title, description, price, image_url, count) {
      this.title = title
      this.description = description
      this.price = price
      this.image_url = image_url
      this.count = count
    }
    //function addIteamToCart(title, description, price,image_url, count){
  this.addNewitem = function addIteamToCart(title, description, price, image_url, count) {
    for (var i in cart) {
      console.log(cart);
      if (cart[i].title === title) {
        cart[i].count += count;
        return;
      }
    }
    var item = new Item(title, description, price, image_url, count);
    console.log(item);
    cart.push(item);
    saveCart();
  }
};



console.log(shoppingCart.newitem(sss,ddd,zzz,sss));

您需要创建一个
ShoppingCart
对象:

var sc = new shoppingCart();
sc.newitem(sss, ddd, zzz, sss);
console.log(sc);

顺便说一句,
cart
变量应该是
shoppingCart
函数的局部变量,而不是全局变量。然后它应该作为一个参数传递给
saveCart()

您的
项目
构造函数应该在
购物车
构造函数之外。永远不要在JS中嵌套类!我担心OP实际上是想做
新的sc.Item(…)
,这将是一个相当反的模式。你能引导他走上正确的道路吗?谢谢Bergi和Barmar@Bergi,它应该是sc.newitem('sss','ddd','zzz','sss')@ChrisTarasovs
sss
对于
count
来说似乎是一个奇怪的值。实际上,我们有5个项目,所以应该是类似于这个sc.newitem('milk','notgood for your',40,false,1);