Javascript 对象。是否创建源解释?
我在看MSDN网络,有人能给我解释一下源代码吗Javascript 对象。是否创建源解释?,javascript,Javascript,我在看MSDN网络,有人能给我解释一下源代码吗 Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype != 'ob
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
,为什么我们要将它设置为null
并返回一个Temp的实例,而我们可以只返回newtemp
Temp.prototype = prototype;
return new Temp;
可能只是为了不缓存最后一个对象,并在原始对象被删除时将其保留在内存中。在绝大多数情况下,这似乎是不必要的,但对于谨慎来说,这并不是一个坏主意