如何通过原型使对象反击?

时间:2015-12-24 19:24:51

标签: javascript

我写了一个脚本,它创建了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 个答案:

答案 0 :(得分: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(); 

答案 1 :(得分:0)

简单计数蘑菇&#39;类&#39;:

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();