Return JavaScript 中的包装对象
Return a wrapped object in JavaScript
我一直在看下划线 _.chain() 函数。我知道它 return 是一个包装对象,调用此对象的方法将继续 return 包装对象,直到调用值。但是,我希望能够在纯 javascript 中执行此操作,但我不确定您将如何 return 在 vanilla js 中包装一个对象。
您可以使用具有 return this
:
函数的对象创建 "wrapped object"
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]
我一直在看下划线 _.chain() 函数。我知道它 return 是一个包装对象,调用此对象的方法将继续 return 包装对象,直到调用值。但是,我希望能够在纯 javascript 中执行此操作,但我不确定您将如何 return 在 vanilla js 中包装一个对象。
您可以使用具有 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]