使用参数对象而不是参数

Use the arguments object instead of parameters

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

我发现这段代码用于javascript的依赖注入实现:

resolve: function() {
  var func, deps, scope, args = [], self = this;
  func = arguments[0];
  deps = func.toString().match(/^function's*[^'(]*'('s*([^')]*)')/m)[1].replace(/ /g, '').split(',');
  scope = arguments[1] || {};
  return function() {
    var a = Array.prototype.slice.call(arguments, 0);
    for(var i=0; i<deps.length; i++) {
        var d = deps[i];
        args.push(self.dependencies[d] && d != '' ? self.dependencies[d] : a.shift());
    }
    func.apply(scope || {}, args);
  }        
}

我想知道为什么那个丑陋的func = arguments[0]在那里,因为我写的只是:function(func) { ... }......有什么区别吗?

有一个区别:

function a(arg) { return arg; };
function b() { return arguments[0]; };
console.log(a.length); // 1
console.log(b.length); // 0

但我认为它更符合使用默认值所必需的arguments[1] || {}