首页 > 解决方案 > 是否可以检测何时在 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 类。仅使用其构造函数。

标签: javascript

解决方案


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

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');

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


推荐阅读