作者ctiml (void)
看板Web_Design
标题Re: [问题] JavaScript的继承问题
时间Thu Jun 27 00:21:58 2013
※ 引述《flyingIdea (飞翔的想法)》之铭言:
: 程式码是在这里看到的
: http://openhome.cc/Gossip/JavaScript/ClassSimulation.html
[恕删]
: 我想请问最後3行为什麽要delete掉?
: 是因为this.x = x这里就会new出来了吗?
: 如果没有delete掉会浪费记忆体?
Cylinder.prototype 物件的 x, y, r 基本上都是 undefined,也不会被用到。
Cylinder 建构式中的 Circle.call(this, x, y, r); 就会帮 new 出来的物件
加上 x, y, r。
关於记忆体浪费,我做了一个简单的小实验。
我从 stackoverflow 找了一段伪 sizeof() 的程式码片段,来计算 object 大小。
(程式码来源:
http://goo.gl/MhCV1)
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
Cylinder.prototype = new Circle();
Cylinder.prototype.constructor = Cylinder;
Object.size(Cylinder.prototype);
// 3
delete Cylinder.prototype.x;
delete Cylinder.prototype.y;
delete Cylinder.prototype.r;
Object.size(Cylinder.prototype);
// 0
虽然是个有点无脑的小实验,但说明了 Cylinder.prototype 的 x, y, r
确实占用了三个单位的空间,而且还不会被用到,小小的浪费 XD
实际上这三个 undefined 究竟占用了多少记忆体,
小弟我不清楚该怎麽精确计算,很抱歉!
希望能帮上一些忙 :)
p.s. 依板规第 2 条,如有违反请告知 ^^" 感谢!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 120.125.113.187
1F:推 flyingIdea:谢谢原PO的解答 06/30 11:45
2F:→ flyingIdea:寄回信箱里再慢慢看~不过我不知道AJAX才是JS的专版Orz 06/30 11:45