在JavaScript中返回一个包装对象

时间:2015-12-08 16:13:33

标签: javascript underscore.js

我一直在看Underscores _.chain()函数。我知道它返回一个包装对象,并且在该对象上调用方法将继续返回包装对象,直到调用value。但是我希望能够在纯javascript中执行此操作,但我不确定如何在vanilla js中返回包装的对象。

1 个答案:

答案 0 :(得分:3)

您可以使用具有return this

功能的对象创建“包装对象”
function _(xs) {
  return {
    map: function(f) {
      xs = xs.map(f)
      return this
    },
    filter: function(f) {
      xs = xs.filter(f)
      return this
    },
    value: function() {
      return xs
    }
  }
}

var result = _([1,2,3]).map(function(x) {
  return x + 1
}).filter(function(x) {
  return x < 4
}).value()

console.log(result) //=> [2, 3]
相关问题