如何实现一个可以在另一个函数中调用的函数,如下例所示?

时间:2018-03-31 06:18:57

标签: javascript require invoke

我想实现一个可以调用的结构,如下例所示:

require("Promotions").getDisounts().getProductDiscounts().getLength();

3 个答案:

答案 0 :(得分:0)

//Promotions.js
export default {
  getDsounts: () => ({
    getProductDiscounts: () => ({
      getLength: () => 20
    })
  })
}

答案 1 :(得分:0)

你的问题很模糊,因此这种个人解释:

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

答案 2 :(得分:0)

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