Why is the Temp.prototype on the MDN Object.create polyfill set to null?

烈酒焚心 提交于 2019-12-19 04:23:10

问题


Why does the MDN polyfill for Object.create have the following line:

Temp.prototype = null;

Is it so that we avoid maintaining a reference to the prototype argument enabling faster garbage collection?

The 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;
    };
  })();
}

回答1:


Yes, exactly. This polyfill does hold the Temp function forever in memory (so that its faster on average, not needing to create a function for every invocation of create), and resetting the .prototype on it is necessary so that it does not leak.




回答2:


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.



来源:https://stackoverflow.com/questions/28550804/why-is-the-temp-prototype-on-the-mdn-object-create-polyfill-set-to-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!