使用原型继承的javascript代码中的对象生存期是什么



我目前正在阅读"Javascript Good Parts",我遇到了以下段落

如果我们尝试从对象中检索属性值,并且对象缺少属性名,则JavaScript尝试检索原型对象的属性值。如果这个物体如果没有属性,则返回其原型,依此类推,直到这个过程最终以Object.prototype.见底

如果我从obj1创建一个对象obj2作为原型,这是否意味着在obj2也超出范围之前,obj1不能被销毁?

只要您已经构建了对象的继承(链接了原型),我不认为浏览器依赖于您对该对象的引用。

ex1:

var a = function(){};
a.prototype.toString = function(){return "I'm an A!";};
var b = new a();
a = undefined;
var c = new a();// error => a is not a function any more!
b.toString();// it works because the prototype is not destroyed, 
             // only our reference is destroyed

ex2:

var a = function(){};
a.prototype.toString = function(){return "I'm an A!";};
var b = function(){};
b.prototype = new a();
a = undefined;
var c = new b();
console.log(c+'');// It still works, although our 
                  // initial prototype `a` doesn't exist any more.

更新:这种行为可能与以下事实有关:在javascript中,您不能完全销毁对象;你只能删除对它的所有引用。之后,浏览器决定如何通过它的垃圾收集器处理未引用的对象。

最新更新