繁体   English   中英

使用方法导出匿名函数

[英]Export anonymous function with methods

有一个关于使用Node.js导出匿名函数的问题这个导出的结果是什么:

var date = require('./index.js'); 
var time = date('2017-05-16 13:45')
.add(24, 'hours')
.subtract(1, 'months')
.add(3, 'days')
.add(15, 'minutes');

在index.js中,我试图导出匿名函数,如

module.exports = function(date){
    return {
        exports: function(date){},
        add: function (value, type) {},
        subtract: function (value, type) {}
    };
}

所以有2个问题:

  1. 它不能通过日期调用('2017-05-16 13:45') - 是否可以定义一个具有返回值的匿名函数的'构造函数'? 如何在自己调用新导入的匿名函数时定义默认行为?
  2. 它无法以time.add()形式调用.subract()。add ...

新的js世界,所以任何帮助将非常感谢!

谢谢你,伊戈尔

  1. 这对我来说似乎是可调用的,您使用的是哪个版本的节点? 你似乎是从./index.js导入你的库 - 这绝对是正确的文件?

  2. 您需要返回this链接方法:

test.js

var date = require('./index.js'); 
var time = date('2017-05-16 13:45')
.add(24, 'hours')
.subtract(1, 'months')
.add(3, 'days')
.add(15, 'minutes');

index.js:

// NB: I've named the outer variable `_data` since you can
// access it from within the other functions (closure)
module.exports = function(_date) {

  return {
    exports: function(date) {
      // do things here

      return this;
    },
    add: function(value, type) {
      // do things here

      return this;
    },
    subtract: function(value, type) {
      // do things here

      return this;
    }
  };
}

如果您不依赖于当前的方法,这里有两个替代方案可以正常用于您的目的:

使用实际的构造函数:

// the benefit here is that your methods don't get recreated for every
// instance of the class

function Date(_date) {
  this.date = _date;
}

Date.prototype = Object.assign(Date.prototype, {
  exports: function(date) {
    // do things here
    console.log(date, this.date);

    return this;
  },

  add: function(value, type) {
    return this;
  },

  subtract: function(value, type) {
    return this;
  }
})

// this function isn't strictly necessary, just here to 
// maintain compatibility with your original code
module.exports = function(date) {
  return new Date(date);
}

有一个普通的老class

class Date {
  constructor(date) {
    this.date = date;
  }

  exports(date) {
    return this;
  }

  add(value, type) {
    return this;
  }

  subtract(value, type) {
    return this;
  }
}

// this function isn't strictly necessary, just here to 
// maintain compatibility with your original code
module.exports = function (date) {
  return new Date(date);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM