pat*_*fox 8 javascript prototype
我目前正在阅读"Javascript Good Parts",我发现了以下段落
如果我们尝试从对象检索属性值,并且对象缺少属性名称,则JavaScript会尝试从原型对象中检索属性值.如果该对象缺少属性,那么它将转到其原型,依此类推,直到该进程最终以Object.prototype结束.
如果我从obj1创建一个对象obj2作为原型,这是否意味着obj1不能被销毁,直到obj2也超出范围?
只要您构建了对象的继承(链接原型),我认为浏览器不依赖于您对该对象的引用.
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
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
更新: 此行为可能与javascript中无法准确销毁对象的事实有关; 你只能删除它的所有引用.之后,浏览器决定如何通过它的垃圾收集器处理未引用的对象.
| 归档时间: |
|
| 查看次数: |
1176 次 |
| 最近记录: |