gpt4 book ai didi

javascript - 是否可以检测 JavaScript 中何时创建 ES6 类的第一个实例?

转载 作者:行者123 更新时间:2023-11-28 12:55:44 25 4
gpt4 key购买 nike

这是我的 JavaScript 类:

class Animal{
constructor(name, sound){
this.name = name;
this.sound = sound;
}
speak(){
console.log(this.name + `${this.sound}`);
}
}

我想在创建 Animal 的第一个实例时执行一些代码。我的意思是:

let dog1 = new Animal('n1', 's1'); //first instance - run my code
let dog2 = new Animal('n2', 'n2');// second instance - do nothing

可以吗?当然,无需更改上面代码中的 Animal 类。仅使用其构造函数。

最佳答案

只需在构造函数中进行检查:

let haveMadeFirstInstance = false;
class Animal{
constructor(name, sound){
this.name = name;
this.sound = sound;
if (!haveMadeFirstInstance) {
console.log('First instance - running some code!');
haveMadeFirstInstance = true;
}
}
speak(){
console.log(this.name + `${this.sound}`);
}
}

console.log('About to create dog1');
let dog1 = new Animal('n1', 's1');
console.log('dog1 has been created');
let dog2 = new Animal('n2', 'n2');
console.log('dog2 has been created');

如果您希望封装自定义代码,请随意将类放入 IIFE 中:

const Animal = (() => {
let haveMadeFirstInstance = false;
return class Animal{
constructor(name, sound){
this.name = name;
this.sound = sound;
if (!haveMadeFirstInstance) {
console.log('First instance - running some code!');
haveMadeFirstInstance = true;
}
}
speak(){
console.log(this.name + `${this.sound}`);
}
}
})();

console.log('About to create dog1');
let dog1 = new Animal('n1', 's1');
console.log('dog1 has been created');
let dog2 = new Animal('n2', 'n2');
console.log('dog2 has been created');

如果您根本无法修改原始类,并且您也无法控制何时创建第一个实例,那么不,您想要做的事情是不可能的。

关于javascript - 是否可以检测 JavaScript 中何时创建 ES6 类的第一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55791999/

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