为什么MDN Object.create polyfill上的Temp.prototype设置为null?

时间:2015-02-16 21:38:42

标签: javascript polyfills

为什么Object.create的MDN polyfill具有以下行:

Temp.prototype = null;

是否因此我们避免维护对原型参数的引用以实现更快的垃圾收集?

polyfill:

if (typeof Object.create != 'function') {
  Object.create = (function() {
    var Temp = function() {};
    return function (prototype) {
      if (arguments.length > 1) {
        throw Error('Second argument not supported');
      }
      if (typeof prototype != 'object') {
        throw TypeError('Argument must be an object');
      }
      Temp.prototype = prototype;
      var result = new Temp();
      Temp.prototype = null;
      return result;
    };
  })();
}

2 个答案:

答案 0 :(得分:3)

是的,确切地说。此polyfill确实将Temp函数永久保存在内存中(因此平均速度更快,不需要为create的每次调用创建函数),并重置.prototype就可以了必要的,以便它不会泄漏。

答案 1 :(得分:1)

I think this is just clean, Temp.prototype is kind of static, since it is set before new Temp() it is nice to clean it after.