首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用方法导出匿名函数

问用方法导出匿名函数
EN

Stack Overflow用户
提问于 2018-02-06 16:04:37
回答 1查看 10K关注 0票数 2

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

代码语言:javascript
复制
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中,我尝试导出匿名函数,例如

代码语言:javascript
复制
module.exports = function(date){
    return {
        exports: function(date){},
        add: function (value, type) {},
        subtract: function (value, type) {}
    };
}

所以它有两个问题:

  1. 它不能通过日期调用(‘2017-05-16 13:45') --是否可以定义一个匿名函数的“构造函数”,并从中返回值?如何定义新导入的匿名函数本身调用时的默认行为?
  2. 它不能在表单time.add().subtract().add中调用.

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

谢谢你,伊戈尔

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-06 16:37:13

  1. 这似乎是可调用的,您使用的是哪个版本的节点?您似乎是从./index.js导入您的库--这绝对是正确的文件吗?
  2. 您需要返回this才能链接方法:

test.js

代码语言:javascript
复制
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:

代码语言:javascript
复制
// 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;
    }
  };
}

如果您没有依附于当前的方法,下面有两种选择,可以很好地满足您的需要:

具有实际的构造函数:

代码语言:javascript
复制
// 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__:

代码语言:javascript
复制
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);
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48647160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档