我想实现一个可以像以下示例一样调用的结构:
require("Promotions").getDisounts().getProductDiscounts().getLength();
//Promotions.js
export default {
getDsounts: () => ({
getProductDiscounts: () => ({
getLength: () => 20
})
})
}
您的问题含糊不清,因此这种个人解释 :
class Collection {
constructor (items) {
this.items = items;
}
getLength () {
return this.items.length;
}
filter (predicate) {
return new Collection(
this.items.filter(predicate)
);
}
}
class Product {
constructor (isDiscount) {
this.isDiscount = isDiscount;
}
}
class Products {
constructor (items) {
this.items = items;
}
getDiscounts () {
return new ProductDiscounts(
this.items.filter(p => p.isDiscount)
);
}
}
class ProductDiscounts {
constructor (items) {
this.items = items;
}
getProductDiscounts () {
return this.items;
}
}
var products = new Products(new Collection([
new Product(true),
new Product(false),
new Product(true)
]));
console.log(products.getDiscounts().getProductDiscounts().getLength());
//proportions.js
var Promotions = function promotions() {
return {
getDiscounts: function getDiscounts() {
return {
getProductDiscounts: function getProductDiscounts() {
return {
getLength: function getLength(){
return 20;
}
}
}
};
}
};
}
module.exports = Promotions();
//main.js
var promotions = require("./promotions.js");
console.log(promotions.getDiscounts().getProductDiscounts().getLength());