Javascript基础知识:访问嵌套函数

Javascript basics: accessing nested-functions

本文关键字:嵌套 函数 访问 基础知识 Javascript      更新时间:2023-09-26

我正在努力学习JavaScript。我正在处理一个问题,我正在制作一个杂货清单:一个包含项目、数量和价格的子数组数组。从那里我计划添加项目、读回列表、删除项目等。我目前的问题是我无法访问子方法。我似乎找不到关于如何做到这一点的文档,但我一直在读这些方法是私人的?所以也许我离基地太远了。我不知道我还能怎么设置,所以多个方法都可以相互对话。

var groceryList = function(food, quantity, price) {
  this.item = {};
  this.items = {food:food, quantity:quantity, price:price};
  return this.items
  this.addStuff = function(food, quantity, price) {
  this.items.push({food:food, quantity:quantity, price:price});
  return this.items
  };
  this.tallyList = function() {
    return items.length;
  }
}

var myList = new groceryList("cookie", 2, 1.00);
console.log(myList)
myList.addStuff("brownie", 1, 2.50);
console.log(myList.tallyList);
var groceryList = function(food, quantity, price) {
    this.items = [];
    this.items.push({food:food, quantity:quantity, price:price});
    var that = this;
    this.addStuff = function(food, quantity, price) {
        that.items.push({food:food, quantity:quantity, price:price});
        return that.items;
    };
    this.tallyList = function() {
        return that.items.length;
    };
    this.getItems = function() {
        return that.items;
    };
    return this;
};
var myList = new groceryList("cookie", 2, 1.00);
console.log(myList);
myList.addStuff("brownie", 1, 2.50);
console.log(myList.tallyList());

这是你想要完成的事情的正确版本。

代码问题:

  1. this.items应该是任何数组,而不是对象。请注意方括号,而不是大括号
  2. 您的构造函数(groceryList函数)并没有返回整个类,它只返回列表/数组。所以你不能调用myList.addStuff()或myList.tallyList()-它们不存在
  3. 请结账";这个";关键词工作?。与其他OO语言不同,JS中的"this"不是指当前的"instance",而是指当前的"scope"。本页对"This"的用法的描述比我所能描述的要好:-)
  4. 我添加了一个额外的函数(getItems())-您现在可以使用获取项目数组

    myList.getItems()

那个代码有点奇怪。

列表是JavaScript中的一个数组,列表中的每一项都可以像处理它一样将其视为一个对象

在您的示例中,groceryList是一个定义私有"方法"的对象。JavaScript和许多其他编程语言中的约定是将"类"命名为UpperCamelCase,所以groceryList就是groceryList。

在"函数"GroceryList中,this表示对象本身,因此您可以将其附加为类似this.addStuff = function ...或"属性"this.items = []的函数。数组变量总是以复数形式调用它们,因为它们包含一组内容。

this.items是食品杂货的数组(列表),每个食品杂货有3个属性:foodquantityprice。您可以使用数组方法this.items.push(grocery)将它们添加到they数组中,其中杂货店是杂货店对象。

var GroceryList = function() {
    this.items = []; // array to store groceries
    // add to object method to add groceries to list
    this.addStuff = function(food, quantity, price) {
        this.items.push({
            food: food,
            quantity: quantity,
            price: price
        });
    };
};
var groceryList = new GroceryList();
groceryList.addStuff('cookie', 2, 1.00);
groceryList.addStuff('brownie', 1, 2.50);
console.log(groceryList.items);

这个"班"里没有什么私人的东西。别担心。

玩小提琴http://jsfiddle.net/42cna2d3/.