我是 JavaScript 新手。我想要一个类方法返回由同一类实例化的对象数组。怎么做?
目前,基本上以下是我所讨论的代码的一般结构。
class myClass{
constructor(name,password,emailid,id) {
this.name = name;
this.password = password;
this.emailid = emailid;
this.id = id;
}
asyncMethod = async()=> {
//method returns array of objects of same class
}
}
在类实例化时(constructor
init), 将当前实例推送到类的static Array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static.
检索您的所有实例通过使用userInstance.getInstances()
(←这是不好的做法!进一步阅读)或User.instances
class User {
static instances = [];
constructor(name, password, emailid, id) {
this.name = name;
this.password = password;
this.emailid = emailid;
this.id = id;
User.instances.push(this); // Push instance into static Class's property
}
getInstances() {
return User.instances; // Return array of instances of same Class
}
}
const A = new User("Cada", "123", "[email protected] /cdn-cgi/l/email-protection", 1);
const B = new User("Roko", "234", "[email protected] /cdn-cgi/l/email-protection", 2);
const C = new User("John", "345", "[email protected] /cdn-cgi/l/email-protection", 3);
console.log(A.name, B.name, C.name); // "Cada", "Roko", "John"
console.log(A.getInstances()); // [User, User, User]
console.log(myClass.instances); // [User, User, User]
密切相关的答案:https://stackoverflow.com/a/61014433/383904 https://stackoverflow.com/a/61014433/383904
我无法解释static
关键字优于MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static:
静态方法和静态属性都不能在类的实例上调用。反而,他们被班级本身召唤. (*ac: myClass.instances
在上面的演示中)
静态方法通常是实用函数,例如创建或克隆对象的函数,而静态属性对于缓存、固定配置或不需要跨实例复制的任何其他数据.
它通常是一个暴露内部结构的不良做法一个类到一个实例。
例如,一个User实例不应该能够从其类构造函数继承整个用户列表。
这是一个使用的轻微变体静态私有 #
和班级Getters get
:
class User {
static #_instances = []; // Static and private
constructor(userData) {
Object.assign(this, userData);
User.#_instances.push(this);
}
static get instances() { // Static to Class
return [...User.#_instances]; // exposes private (as immutable)
}
}
const A = new User({name:"Cada", password:"123", emailid:"[email protected] /cdn-cgi/l/email-protection", id:1});
const B = new User({name:"Roko", password:"234", emailid:"[email protected] /cdn-cgi/l/email-protection", id:2});
console.log(A.name, B.name); // "Cada", "Roko",
console.log(A.instances); // undefined ????
console.log(User.instances); // [User, User] ????
User.instances.push({name:"EVIL!"}); // ????
console.log(User.instances); // [User, User] ????
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)