gpt4 book ai didi

javascript - 是否可以将对象计为 "whole"?

转载 作者:行者123 更新时间:2023-11-29 18:25:22 25 4
gpt4 key购买 nike

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

 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 。

谢谢:)

最佳答案

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

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

另一个想法是向 Student 原型(prototype)添加一个计数器:

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

关于javascript - 是否可以将对象计为 "whole"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14029246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com