嵌套构造函数的最佳实践

时间:2016-12-03 21:35:01

标签: javascript oop

我对JS中的OOP比较新,所以请跟我说一下。

假设我有一个Restaurant构造函数。我想将通过构造函数创建的Menu个对象分配给每个餐馆。但是,我希望能够在Restaurant的方法中访问父Menu的属性。

这样做的最佳方式是什么?

此代码完成工作:

    // Restaurant constructor
    function Restaurant(name, inventory){
        this.name = name;
        this.inventory = inventory;

        var self = this;

        // Menu constructor
        this.Menu = function(items){
            this.items = items;

            // Checks whether an item is available in the menu AND the restaurant's stock
            this.isAvailable = function(item){
                if(this.items.indexOf(item) !== -1 && self.inventory.indexOf(item) !== -1){
                    console.log(item + ' is available in ' + self.name)
                }else{
                    console.log(item + ' is not available in ' + self.name);
                }
            }
        }

    }

    // First restaurant and its menus
    var Diner = new Restaurant('diner', ['steak', 'fish', 'salad']);
    var Entrees = new Diner.Menu(['steak', 'fish']);
    var Appetizers = new Diner.Menu(['shrimp']);

    // Not available, since salad isn't in the menu
    Entrees.isAvailable('salad');
    // Available, since fish is in stock and in the menu
    Entrees.isAvailable('fish');
    // Not available, since shrimp is not in stock
    Appetizers.isAvailable('shrimp');

    // Different restaurant and its menus
    var BurgerJoint = new Restaurant('burger joint', ['burger', 'fries', 'ketchup']);
    var Sides = new BurgerJoint.Menu(['ketchup', 'fries']);
    var Lunch = new BurgerJoint.Menu(['fries', 'burger', 'mustard']);

    Sides.isAvailable('salad');
    Sides.isAvailable('fries');
    Lunch.isAvailable('mustard');

但是,这会导致isAvailable方法(和其他类似方法)无法移动到原型的缺陷,因为它们依赖于Restaurant属性的self属性。最接近的是将Menu构造函数替换为:

        var self = this;

        // Menu constructor
        this.Menu = function(items){
            this.items = items;
        }
        this.Menu.prototype = {
            isAvailable:function(item){
                //...
            }
        }

然而,这仍然会为每个Restaurant创建一个新原型,尽管它确实在餐馆的菜单中共享原型。仍然感觉不太理想。

另一个选项是将Menu构造函数与Restaurant取消关联,并在创建新菜单时传入Restaurant对象。像这样:

    // Restaurant constructor
    function Restaurant(name, inventory){
        this.name = name;
        this.inventory = inventory;
    }

    // Menu constructor
    function Menu(restaurant, items){
        this.restaurant = restaurant
        this.items = items;
    }

    Menu.prototype = {
        isAvailable:function(item){
            if(this.items.indexOf(item) !== -1 && this.restaurant.inventory.indexOf(item) !== -1){
                console.log(item + ' is available in ' + this.restaurant.name)
            }else{
                console.log(item + ' is not available in ' + this.restaurant.name);
            }
        }
    }

新菜单的创建方式如下:

    var Entrees = new Menu(Diner, ['steak', 'fish']);

这感觉不对,主要是因为语法不直观,MenuRestaurant本身没有联系。

那么,这样做的正确方法是什么?这些都是?完全不同的方式?

2 个答案:

答案 0 :(得分:1)

原型是你构建UPON的东西,不构建新的东西。例如,你有:

iOS 10.1

...实际上用一个对象替换原型......虽然你不会因为这样做而入狱,但它确实要求你在那个对象的上下文中做所有的“构造”。呸。

这是一个基于您的情况的模型,将为您提供良好的前进。多年来我一直在使用这种方法。它非常灵活和可扩展 - 并且感觉(和有点看起来像)“真正的”编程(例如java,C#等),而不是有趣的goo jquery。

你会注意到我们通过一个整洁的“p”变量构建INTO原型。我还想推迟初始化函数,以便我们可以将构造函数保持在顶部。

    this.Menu.prototype = {
        isAvailable:function(item){
            //...
        }
    }

对于它的价值,我还想将每个类包装成一个闭包,并将每个类作为它自己的文件:

// ------------------------
// Restaurant "class"
// ------------------------
function Restaurant(params){
    this.init(params);
}

var p = Restaurant.prototype;

    // I like to define "properties" on the prototype here so I'm aware of all the properties in this "class"
    p.name = null;
    p.inventory = null; // Don't put arrays or objects on the prototype. Just don't, initialize on each instance.
    p.menus = null;

    p.init = function(params){
        this.name = params.name;
        this.inventory = params.inventory || []; // default to empty array so indexOf doesn't break
        this.menus = {};

        if(params.menus){
            for(var prop in params.menus){
                this.addMenu(prop, params.menus[prop]);
            }
        }

    }

    p.addMenu = function(name, items){
        this.menus[name] = new Menu({
            restaurant : this,
            items : items
        });
    }

    p.getMenu = function(name){
        return this.menus[name];
    }

// ------------------------
// Menu "class"
// ------------------------
function Menu(params){
    this.init(params);
}

var p = Menu.prototype;

    p.items = null;
    p.restaurant = null;

    p.init = function(params){
        this.items = params.items || []; // default to an empty array
        this.restaurant = params.restaurant;
    }

    p.isAvailable = function(item){
        if(this.items.indexOf(item) !== -1 && this.restaurant.inventory.indexOf(item) !== -1){
            console.log(item + ' is available in ' + this.restaurant.name)
        }else{
            console.log(item + ' is not available in ' + this.restaurant.name);
        }
    }

// First restaurant and its menus
var Diner = new Restaurant({
    name        : 'diner',
    inventory   : ['steak', 'fish', 'salad'],
    menus : {
        entrees     : ['steak', 'fish'],
        // appetizers   : ['shrimp'] // maybe add this a different way (below)
    }

});

// ... add a menu another way
Diner.addMenu('appetizers', ['shrimp']);



// Not available, since salad isn't in the menu
Diner.menus.entrees.isAvailable('salad');
// Available, since fish is in stock and in the menu
Diner.getMenu('entrees').isAvailable('fish');
// Not available, since shrimp is not in stock
Diner.menus.appetizers.isAvailable('shrimp');
// or
// Diner.getMenu('appetizers').isAvailable('shrimp');

我会在开发过程中将其放入自己的文件中,只需执行一次< script src =“...”>将每个类放入我的HTML中。然后,为了生产,我可以组合所有文件。

根据这种方法,使用它将是:

// ------------------------
// Restaurant "class"
// ------------------------

// Start the closure
this.myApp = this.myApp || {};
(function(){


// All this is the same as above ...
function Restaurant(params){
    this.init(params);
}

var p = Restaurant.prototype;

    p.init = function(){
    ... yada ...


// Here we finish the closure and add the primary function as a property
//  to the "myApp" global object. So I'm essentially building up "myApp"
// kinda the same way as we built up the prototype.
    myApp.Restaurant = Restaurant;
());

希望这有帮助。

答案 1 :(得分:0)

对象层次结构不应反映为构造函数嵌套。事实上,您所做的不是继承,而是 组合

因此,您应该将每个实体定义为顶级构造函数,并使用实际实例创建对象图:

var menu = new Menu();
var restaurant = new Restaurant(menu);

是什么表明餐厅菜单?餐厅将以这种方式访问​​其菜单:restaurant.menu

在面向对象编程中,是动词表示继承,而具有动词表示聚合

如何将菜单与具体餐厅联系起来?

就是这样:

var menu = new Menu();
var restaurant = new Restaurant(menu);
menu.restaurant = restaurant;

这将是一对一关联。您可能需要在许多餐馆共享菜单。然后你会这样做:

var menu = new Menu();
var restaurant = new Restaurant(menu);
menu.restaurants.push(restaurant);

因此Menu构造函数应初始化this.restaurants

function Menu() {
    this.restaurants = [];
}