为什么 MDN Object.create polyfill 上的 Temp.prototype 设置为空?
Why is the Temp.prototype on the MDN Object.create polyfill set to 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
必要的,这样它就不会泄漏。
我认为这很干净,Temp.prototype 有点静态,因为它是在 new Temp() 之前设置的,所以在之后清理它很好。
为什么 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
必要的,这样它就不会泄漏。
我认为这很干净,Temp.prototype 有点静态,因为它是在 new Temp() 之前设置的,所以在之后清理它很好。