在Javascript中,有没有一种方法可以计算我创建了多少个对象?

4
例如,假设我非常饥饿,所以我一直在制作煎饼!
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?");

我刚做了多少个煎饼?有没有一个代码可以告诉我“这里有这么多个变量是Pancake类型的”?感谢答复!我特别想寻找一种简单的方法来快速计算创建对象的次数,而这就是我的所得,谢谢!

你能添加你的Pancake类吗? - Satej S
1
相当肯定你得手动做... - James
可能是一个重复问题,参考如何计算对象的实例数量? - Nidhin David
6个回答

5
您可以在 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;
       }
    };
}());

或将它们放置在对象原型中:
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
}

您可以通过实现某种"继承"来 "覆盖" 构造函数,例如在此 fiddle 中:

var Pancake = function(a, b) {
 this.a = a;
  this.b = b;
};

var before = Pancake.prototype;
var Pancake = function() {
 console.log("overriden");
 Pancake.prototype.instances = Pancake.prototype.instances ? Pancake.prototype.instances + 1 : 1; // here you should restore the whole prototype
  return before.constructor.apply(this, arguments);
};


var a = new Pancake("a", "b");
document.write(Pancake.prototype.instances + "<br />");
var b = new Pancake("c", "d");
document.write(Pancake.prototype.instances + "<br />");

document.write(JSON.stringify(a) + "<br />");
document.write(JSON.stringify(b) + "<br />");


非常感谢!哇,我简直不敢相信我没有做过那个!我完全忘记它们是函数而不仅仅是对象! - Raymond
1
@Raymond,您不会想要手动创建它吧!?这是您的问题所说的吗? - Nidhin David
@NidhinDavid 噢,我手动的意思是每次我创建一个新实例后,就将其添加到某个东西中。所以每次新建一个Pancake之后,我都会将1添加到计数器或其他东西里。我没有意识到我可以在函数中加入一小段代码(我只需加入count++),这样每次我创建新实例时都会自动加上。 - Raymond

2

1
啊,那确实有帮助!我不是最擅长编程的人,所以具体细节和示例对我来说有点混淆(这就是为什么我用煎饼作为例子的原因)。不过还是谢谢你! - Raymond

1
在Pancake函数中使用计数器变量。 :)
var count = 0;
function Pancake(){
// Cook pancakes
count += 1;
}

console.log('Total pancakes' + count);

谢谢!我明白了,非常简单易懂的答案!谢谢! - Raymond

0

我知道你已经接受了一个答案,但这花费了我一些时间!从你的问题中,我想你可能不想改变Pancake类。因此,这里尝试避免这种情况。

这个函数将搜索您指定的对象中的所有对象,并计算您类型的所有实例的数量。

    // Usage: 
    searchObjectForType(window, Pancake); // returns a number.

    function searchObjectForType(obj,type){
        // Keep track of objects in stack so we don't overflow by searching into the same objects;
        var stackObjs = [];

        function recursiveProbe(obj){
          var foundCount = 0;
          var objType;
          // Some types will throw (iframes/nulls/..)
          try{
            objType = obj.toString();
          }
          catch(err){
            return 0;
          }
           // Skip document/previous objects as we know they won't have any.
          if(typeof obj === "string" || stackObjs.indexOf(objType)>=0 || obj===document){
            return 0;
          }
          else{
            stackObjs.push(objType);  
          }

          for (var i in obj){
            var prop = obj[i];
            if(prop instanceof type){
                foundCount++; 
            }
            else{
                foundCount += recursiveProbe(prop);
            }   
          }
          // Remove this type from stackObjs so we can search future types.
          stackObjs.splice(stackObjs.indexOf(obj.toString()),1);
          return foundCount;
        }

        return recursiveProbe(obj);
    }            

我相信有些情况下这种方法可能会失败,所以欢迎反馈!


0

更面向对象的方法是使用静态方法和静态属性。 虽然JS没有静态属性,但我们可以在构造函数本身上设置它 例如:

class Pancake {
    static count() {
        Pancake.counter = (Pancake.counter || 0) + 1;
        return;
    }
    constructor(objName) {
        Pancake.count();
        this.name = objName;
    }
}


new Pancake("A");
console.log(Pancake.counter);  //1
new Pancake("B");
console.log(Pancake.counter);  //2
new Pancake("C");
console.log(Pancake.counter);  //3
new Pancake("D");
console.log(Pancake.counter);  //4
new Pancake("E");
console.log(Pancake.counter);  //5

示例:https://jsfiddle.net/mux2qnsc/


0
如果您想要计算从原型创建的实例数量,您需要一个类似于以下的属性:
Asset.prototype.index = 0;

现在,在构造函数本身中使用:
function Asset () {
    this.index = Asset.prototype.index++;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接