簡體   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