严格模式下 "arguments.callee" 的替代方案

368 阅读1分钟

在严格模式下是禁用 arguments.callee 函数的,此时需要对方法做一定的修改,例如原方法使用arguments.callee 函数:

Object.deepExtend = function (destination, source) {
  for (var property in source) {
    if (source[property] && source[property].constructor &&
     source[property].constructor === Object) {
      destination[property] = destination[property] || {};
      arguments.callee(destination[property], source[property]);
    } else {
      destination[property] = source[property];
    }
  }
  return destination;
};

我们修改为一个名为fn()的命名函数表达式,然后将它赋值给变量Object.deepExtend,即是把函数赋值给另外一个变量,函数的名字仍然有效。修改后的函数:

Object.deepExtend = (function fn(destination, source) {
  for (var property in source) {
    if (source[property] && source[property].constructor &&
     source[property].constructor === Object) {
      destination[property] = destination[property] || {};
        // 修改后
        fn(destination[property], source[property]);
    } else {
      destination[property] = source[property];
    }
  }
  return destination;
});