javascript - 是否可以检测何时在 JavaScript 中创建 ES6 类的第一个实例?
问题描述
这是我的 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');
如果您根本无法修改原始类,并且您也无法控制何时创建第一个实例,那么不,您想要做的事情是不可能的。
推荐阅读
- linux - 在 Linux Mint 19.1 cinnamon 上配置 pytorch-kaldi 时出错
- reactjs - 从打字稿中的对象破坏属性
- makefile - 使用 autoconf 链接外部对象文件 (.o)
- php - 如何立即从数据库中检索数据然后插入?
- javascript - Vue.js 动态组件未创建但显示在控制台中
- firebase - 当路径中的数据不存在时,如何使用 Go Firebase-Admin SDK 检测空结果
- r - 使用 dplyr 将多列连接为一列
- c++ - GCC:为局部变量指定 mmx 寄存器失败
- c# - Azure 配置未显示在门户中
- python-3.x - Python 对象实例未保存在 Flask 应用程序上下文中