Ben Aston Ben Aston - 1 year ago 188
Javascript Question

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

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;

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download