2

我可以数一个物体吗?喜欢:

 var student1 = new Student();
student1.name("ziv");
student1.age();
student1.where("a");


 var student2 = new Student();
student2.name("dani");
student2.age();
student2.where("b");

 var student3 = new Student();
student3.name("bari");
student3.age();
student3.where("c");

一些计算它们并返回 3 的函数。

谢谢 :)

4

4 回答 4

2

我想你的意思是计数实例。您必须跟踪实例,例如使用数组

var students = [];
var student1 = new Student()
   ,student2 = new Student();
students.push(students1,students2);
/* later ... */
var nOfStudents = students.length; //=> 2

另一个想法是在Student原型中添加一个计数器:

Student.prototype.instanceCnt = 0;

并在每个实例的 Student 构造函数中递增它

   //in the Student constructor function
   function Student(){
     this.instanceCnt += 1;
     /* ... */
   }
   // usage example
   var student1 = new Student()
      ,student2 = new Student()
      ,students = student1.instanceCnt; //=> 2
于 2012-12-25T09:23:36.913 回答
1

不,您需要手动在Student构造函数中添加一个计数器或将每个实例附加到一个数组并获取该数组的长度。

前:

var counter;
function Student() {
    counter++; // this will increase every time Student is initialized
    // continue the constructor...
}

或者:

var students = [];
function Student() {
    students.push(this); // this will hold the instance in an array
    // continue the constructor...
}
console.log(students.length);
于 2012-12-25T09:12:37.820 回答
1

Javascript 中没有静态的概念,但您可以使用闭包来模拟该功能。

(function(){

  var numberOfInstances = 0;

  var Student = function(studentName){
    var name = '';

    var _init(){
      name = studentName ? studentName : 'No Name Provided';
      numberOfInstances++;    
    }();

    this.getName = function(){
       return name;
    }; 

    this.getNumberOfInstances = function(){
      return numberOfInstances;
    };

    return this;
  };
})(); 

var student1 = new Student("steve");
var student2 = new Student("sally");
console.log("my name is " + student1.getName());
console.log("my name is " + student2.getName());
console.log("number of students => " + student1.getNumberOfInstances());  
console.log("number of students => " + student2.getNumberOfInstances());  
于 2012-12-25T09:15:10.380 回答
0

您可以编写一个简单的通用实例化/继承助手,它在数组中跟踪其实例

像这样的事情可能会做到

var base = (function baseConstructor() {

  var obj = {
    create:function instantiation() {
        if(this != base) {
        var instance = Object.create(this.pub);
         this.init.apply(instance,arguments);
         this.instances.push(instance);
        return instance;
        } else {
          throw new Error("You can't create instances of base");
        }
    },
    inherit:function inheritation() {
      var sub = Object.create(this);
      sub.pub = Object.create(this.pub);
      sub.sup = this;
      return sub;
    },
    initclosure:function initiation() {},
    instances: [],
    pub: {}

  };



  Object.defineProperty(obj,"init",{
   set:function (fn) {
     if (typeof fn != "function")
       throw new Error("init has to be a function");
     if (!this.hasOwnProperty("initclosure"))      
       this.initclosure = fn;
    },
    get:function () {
        var that = this;
        //console.log(that)
            return function() {
              if(that.pub.isPrototypeOf(this)) //!(obj.isPrototypeOf(this) || that == this))
                that.initclosure.apply(this,arguments);
              else
                throw new Error("init can't be called directly"); 
             };
    }    

  });


  Object.defineProperty(obj,"create",{configurable:false,writable:false});
    Object.defineProperty(obj,"inherit",{configurable:false,writable:false});
  return obj;
})();

var Student = base.inherit()
    Student.init = function (age) {
    this.age = age;    
    }

var student1 = Student.create(21)
var student2 = Student.create(19)
var student3 = Student.create(24)

    console.log(Student.instances.length) // 3

这是一个关于JSBin的例子

于 2012-12-25T10:08:41.310 回答