对象创建源解释

Object.create source explanation?

本文关键字:解释 创建 对象      更新时间:2023-09-26

我正在查看MSDN网络,谁能解释一下source-code

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;
    };
  })();
function Guru(name){
   this.name = name;
}

function Shankar(name){
   this.name = name;
}
Guru.prototype = Object.create(Shankar.prototype);

这里让我感到困惑的是Temp.prototype = null;,为什么我们将其设置为 nullreturning a instance of Temp我们可以返回new Temp

Temp.prototype = prototype;
return new Temp;

可能只是为了不缓存最后一个对象并在原始对象被删除时将其保留在内存中。在绝大多数情况下似乎没有必要,但对于谨慎来说并不是一个坏主意。