这是我的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类。仅使用其构造函数。
答案 0 :(得分:5)
只需在构造函数中进行检查:
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');
如果您根本无法修改原始类,并且您也无法控制何时创建,那么不行,您要执行的操作就不可能。
答案 1 :(得分:0)
您可以使用这样的静态属性:
class Animal{
constructor(name, sound){
if(!Animal.instance) {
console.log('First instance');
this.name = name;
this.sound = sound;
Animal.instance = this;
}
}
speak(){
console.log(this.name + `${this.sound}`);
}
}
let dog1 = new Animal('n1', 's1'); //first instance - run my code
let dog2 = new Animal('n2', 'n2');// second instance - do nothing
console.log('dog1: ', dog1);
console.log('dog2: ', dog2);