javascript – 为什么MDN Object.create polyfill上的Temp.prototype设置为null?
作者:互联网
为什么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;
};
})();
}
解决方法:
对,就是这样.这个polyfill确实将Temp函数永久保存在内存中(因此它的平均速度更快,不需要为每次调用create创建一个函数),并且重置.prototype是必要的,这样它就不会泄漏.
标签:polyfills,javascript 来源: https://codeday.me/bug/20191007/1864927.html