首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过原型制作物体计数器?

如何通过原型制作物体计数器?
EN

Stack Overflow用户
提问于 2015-12-24 19:24:50
回答 2查看 206关注 0票数 0

我写了一个脚本,它创建了3个对象。构造函数有一个局部变量mushroomsCount

代码语言:javascript
复制
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

码页

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-24 19:42:00

您可以在Mushroom itselft上使用一个属性(就像您已经拥有的那样,但没有访问)。

代码语言:javascript
复制
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();

或者用一段生活结束:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2015-12-24 19:50:52

蘑菇“类”的简单计数实例:

代码语言:javascript
复制
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(); 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34457117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档