2015-12-24 38 views
0

我寫了一個腳本,它創建了3個對象。構造函數有一個局部變量mushroomsCount如何通過原型製造對象?

Mushroom = function(num) { 
    var mushroomsCount = 0; 

    this.id = num; 
    this.Create(); 
} 

Mushroom.prototype.Create = function() { 
    this.mushroomsCount++; 
} 

Mushroom.prototype.Display = function() { 
    console.log('mushromms count total is: ' + Mushroom.mushroomsCount); 
} 

$(document).ready(function() { 
    var mushroom = []; 
    mushroom[0] = new Mushroom(0); 
    mushroom[1] = new Mushroom(1); 
    mushroom[2] = new Mushroom(2); 

    mushroom[2].Display(); // first way 
    Mushroom.Display();  // second way 

}); 

創建對象後,我嘗試Mushroom.prototype.Display()顯示對象的數目,但我越來越undefined

codepen

+2

變量和對象屬性之間沒有關係。你的'var mushroomsCount'與'this.mushroomsCount'和'Mushroom.mushroomsCount'完全不同。 –

回答

1

您可以在Mushroom itselft使用屬性(如你已經有了,但沒有訪問)。

function Mushroom(num) { 
 
    this.id = num; 
 
    this.create(); 
 
} 
 
Mushroom.mushroomCount = 0; // this is public! 
 
Mushroom.prototype.create = function() { 
 
    Mushroom.mushroomCount++; 
 
} 
 

 
Mushroom.prototype.display = function() { 
 
    document.write('mushromms count total is: ' + Mushroom.mushroomCount + '<br>'); 
 
} 
 

 
var mushroom = []; 
 
mushroom[0] = new Mushroom(0); 
 
mushroom[1] = new Mushroom(1); 
 
mushroom[2] = new Mushroom(2); 
 
mushroom[0].display(); 
 
mushroom[1].display(); 
 
mushroom[2].display();

或者使用閉包與IIFE:蘑菇 '階級' 的

var Mushroom = function() { 
 
    var mushroomCount = 0; 
 
    var f = function (num) { 
 
     this.id = num; 
 
     this.create(); 
 
    }; 
 
    f.prototype.create = function() { mushroomCount++; } 
 
    f.prototype.display = function() { document.write('mushromms count total is: ' + mushroomCount + '<br>'); } 
 
    return f; 
 
}(); 
 

 
var mushroom = [new Mushroom(0), new Mushroom(1), new Mushroom(2)]; 
 
mushroom[0].display(); 
 
mushroom[1].display(); 
 
mushroom[2].display();

+0

將IIFE包裝在括號中是一種常見的做法,因此從一開始就更容易判斷它們是否爲IIFE。 – RobG

0

簡單計數實例:

function Mushroom(num) { 
    this.id = num; 
    Mushroom.count++; 
} 
Mushroom.count = 0; 
Mushroom.prototype.Display = function() { 
    document.write('mushromms count total is: ' + Mushroom.count + '<br>'); 
} 

var mushroom = []; 
mushroom[0] = new Mushroom(0); 
mushroom[1] = new Mushroom(1); 
mushroom[2] = new Mushroom(2); 
mushroom[2].Display();