【问题标题】:In Javascript, is there a way to count how many created objects I've made?在 Javascript 中,有没有办法计算我创建了多少个创建的对象?
【发布时间】:2016-09-08 03:14:36
【问题描述】:

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

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

如果没有手动操作,我如何计算我刚做了多少煎饼?是否有代码显示“煎饼品种有这么多变量”?

编辑:

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

【问题讨论】:

标签: javascript variables object counting


【解决方案1】:

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

您还可以通过实现某种“继承”来“覆盖”构造函数,例如在这个小提琴中:

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 以为您不想手动创建它!这就是你的问题所说的!?
  • @NidhinDavid 啊,手动我的意思是每次我创建一个我喜欢的对象的新实例时,添加一些东西。所以在每一个新的煎饼之后,我都会在计数上加 1 或其他东西。我没有意识到我可以只在函数中放入一点点代码(我实际上只是放入了 count++),并且每次我创建一个新实例时它都会添加。
【解决方案2】:

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

How can I count the instances of an object?

【讨论】:

  • 啊,确实有帮助!我不是最擅长编码,所以细节和例子让我有点困惑(为什么我用煎饼作为例子)谢谢!
【解决方案3】:

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

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

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

【讨论】:

  • 谢谢!我明白了这一点,非常简单的答案!谢谢!
【解决方案4】:

我知道你已经接受了一个答案,但这花了我一段时间!根据您的问题,我认为您可能不想更改 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);
    }            

我确信在某些情况下会失败,因此感谢您的反馈!

【讨论】:

    【解决方案5】:

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

    Asset.prototype.index = 0;
    

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

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

    【讨论】:

      【解决方案6】:

      更面向对象的方法是使用静态方法和静态属性。 虽然 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/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-01
        • 2020-06-06
        • 2012-05-13
        • 2014-11-26
        • 2018-04-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多