gpt4 book ai didi

javascript - 嵌套构造函数的最佳实践

转载 作者:行者123 更新时间:2023-12-03 05:30:53 25 4
gpt4 key购买 nike

我对 JS 中的 OOP 还比较陌生,所以请耐心等待。

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

最好的方法是什么?

这段代码完成了这个工作:

    // 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 方法(和其他类似方法)无法移动到原型(prototype),因为它们依赖于通过 self< 获取 Restaurant 的属性。/ 属性。最接近的方法是将 Menu 构造函数替换为:

        var self = this;

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

然而,这仍然为每个Restaurant创建一个新的原型(prototype),尽管它确实在餐厅的菜单之间共享原型(prototype)。感觉还是不太理想。

另一个选项是取消 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']);

这感觉不对,主要是因为语法不直观,并且菜单本身并没有与餐厅链接。

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

最佳答案

原型(prototype)是您在 PON 上构建的东西,而不是构建新的。例如,您有:

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

...这本质上是用一个对象替换原型(prototype)...虽然您不会因此而入狱,但它确实要求您在该一个对象的上下文中完成所有“构造”。恶心。

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

您会注意到我们通过一个简洁的“p”变量构建了原型(prototype)。我还喜欢推迟对函数的初始化,这样我们就可以将构造函数保持在顶部。

// ------------------------
// 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');

就其值(value)而言,我还喜欢将每个类包装到一个闭包中,并将每个类作为它自己的文件:

// ------------------------
// 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;
());

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

在这种方法下,使用它的方法是:

var Diner = new myApp.Restaurant({
name : 'diner',
inventory : ['steak', 'fish', 'salad'],
menus : {
entrees : ['steak', 'fish'],
// appetizers : ['shrimp']
}

});

// ... and the rest is the same as above.

希望这有帮助。

关于javascript - 嵌套构造函数的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40952737/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com