在 Javascript 中,有没有办法计算我创建了多少个创建的对象?

In Javascript, is there a way to count how many created objects I've made?

比如,假设我真的很饿,所以我就继续做煎饼!

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?");

如果不手动操作,我如何计算我刚做了多少个煎饼?是否有代码显示 "There are this many variables that are of the Pancake variety"?

编辑:

感谢您的解答!我专门在寻找一种简单的方法来快速计算我用少量代码创建对象的次数。这就是我得到的,谢谢!

在 Pancake 函数中使用计数器变量。:)

var count = 0;
function Pancake(){
// Cook pancakes
count += 1;
}

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

你可以保留一个计数器,它会在构造函数中增加,这是一个很好的解决方案

How can I count the instances of an object?

您可以在 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
}

您还可以 "override" 构造函数,通过实现某种 "inheritance",例如 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 />");

我知道你已经接受了一个答案,但这花了我一段时间!根据你的问题,我认为你可能不想更换煎饼 class。因此,这里尝试避免这种情况。

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

    // 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);
    }            

我敢肯定在某些情况下会失败,因此欢迎提供反馈!

如果您想计算从原型创建的实例数,您需要 属性 如:

Asset.prototype.index = 0;

现在,在构造函数中使用:

function Asset () {
    this.index = Asset.prototype.index++;
}

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

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/