Re: [問題] JavaScript的繼承問題
※ 引述《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
推
06/30 11:45, , 1F
06/30 11:45, 1F
→
06/30 11:45, , 2F
06/30 11:45, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):