gpt4 book ai didi

javascript - 使用原型(prototype)继承的javascript代码中的对象生命周期是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 04:16:15 25 4
gpt4 key购买 nike

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

If we try to retrieve a property value from an object, and if the object lacks the property name, then JavaScript attempts to retrieve the property value from the prototype object. And if that object is lacking the property, then it goes to its prototype, and so on until the process finally bottoms out with Object.prototype.

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

最佳答案

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

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 中您无法完全销毁对象;您只能删除对它的所有引用。之后,浏览器通过它的 Garbage collector 决定如何处理未引用的对象。 .

关于javascript - 使用原型(prototype)继承的javascript代码中的对象生命周期是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8891112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com