使用变量作为对象和函数

Using a variable as an object and a function

本文关键字:对象 函数 变量      更新时间:2023-09-26

我试图模拟JavaScript库Underscore.js中的times函数。

这个函数接受两种语法:

_.times(3, function(n) {
    console.log("hello " + n);
});

_(3).times(function(n) {
    console.log("hello " + n);
});
到目前为止,我通过创建一个_对象成功地模拟了第一个对象,如下所示:
var _ = {
    times: function(reps, iteratee) {
        // a loop
    }
};

第二种语法通过创建一个_函数返回一个对象:

function _(n) {
    return {
        times: function(iteratee) {
            // a loop
        }
    };
}

但是我不能同时使用这两种方法。我需要找到一种同时允许这两种语法的方法。您知道我如何使用_字符作为对象以及函数吗?

您应该能够像这样组合两种语法:

var _ = (function() {
    var times = function(n, iteratee) {
        // a loop
    };
    function _(n) {
        return {times: function(iteratee) {
            return times(n, iteratee);
        }}; // or shorter: {times: times.bind(null, n)}
    }
    _.times = times;
    return _;
})();

在这里你受益于函数也是对象,因此可以有属性。

函数在Javascript中是对象,所以你可以这样做:

var _ = function(a,b) { /* ... */ };
_.times = _;

可以在定义函数后扩展它。试试这个:

function _(n) {
  return {
    times: function(iteratee) {
      while (n-- > 0)
        iteratee();
    }
  };
}
_.times = function(reps, iteratee) {
  while (reps-- > 0)
    iteratee();
};
function iter() {
  console.log('iter!');
}
_(3).times(iter);
console.log('----');
_.times(5, iter);