简体   繁体   English

使用arguments对象代替参数

[英]Use the arguments object instead of parameters

I found this piece of code used in a dependency injection implementation in javascript: 我发现这段代码在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);
  }        
}

And I was wondering myself why that ugly func = arguments[0] was there, because I'd write that with just: function(func) { ... } ... is there any difference? 而且我想知道为什么那儿有丑陋的func = arguments[0] ,因为我会这样写: function(func) { ... } ...有什么区别吗?

There is a difference: 有区别的:

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

But I think it more to be compatible with arguments[1] || {} 但是我认为与arguments[1] || {}兼容arguments[1] || {} arguments[1] || {} which is necessary to use the default value. arguments[1] || {} ,这是使用默认值所必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM