Ray*_*ond 4 javascript variables object counting
例如,假设我真的很饿,所以我就继续做煎饼!
var Buttermilk = new Pancake("Buttermilk", "Delicious");
var ChocolateChip = new Pancake("Chocolate Chip", "Amazing");
var BlueBerry = new Pancake("Blue Berry", "The Best");
var SnozBerry = new Pancake("Snoz Berry", "What's a Snoz Berry?");
Run Code Online (Sandbox Code Playgroud)
如果不手动做,我如何计算我刚做了多少煎饼?是否有代码说“煎饼品种有这么多变量”?
编辑:
谢谢你的回答!我一直在寻找一种简单的方法来快速计算我用少量代码创建对象的次数。这就是我得到的,谢谢!
您可以在 javascript 类中拥有静态属性。您可以通过这种方式将它们隐藏在闭包中:
var Pancake = (function() {
var instances = 0;
return function(a, b) {
this.a = a;
this.b = b;
instances++;
Pancake.prototype.instances = function() { // equivalent of a static method
return instances;
}
};
}());
Run Code Online (Sandbox Code Playgroud)
或将它们放在对象原型中:
var pancake = function(a, b) {
this.a = a;
this.b = b;
pancake.prototype.count = pancake.prototype.count ? pancake.prototype.count + 1 : 1; // equivalent of a static property
}
Run Code Online (Sandbox Code Playgroud)
您还可以通过实现某种“继承”来“覆盖”构造函数,例如在这个小提琴中:
var Pancake = (function() {
var instances = 0;
return function(a, b) {
this.a = a;
this.b = b;
instances++;
Pancake.prototype.instances = function() { // equivalent of a static method
return instances;
}
};
}());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2698 次 |
| 最近记录: |