如何检测EcmaScript类是否有自己的构造函数? 请参阅下面的代码片段。
class Person {
constructor(name, age) { // <- Own constructor
this._name = name;
this._age = age;
}
}
class Manager extends Person {
// This class does not have it's own constructor
}
似乎没有明确的方法来进行此检查。
感谢大家的时间和帮助。
最佳答案
它不是防弹的,但您可以将构造函数转换为字符串,并查看它是否包含单词 constructor(
或类似的内容
function hasOwnConstructor(instance) {
var str = instance.constructor.toString();
return /class(.*?[^\{])\{([\s\n\r\t]+)?(constructor[\s]+?\()/.test(str);
}
class thing1 {
method() { return this; }
}
class thing2 {
constructor(argument) { return this; }
}
var ins1 = new thing1();
var ins2 = new thing2();
console.log( hasOwnConstructor(ins1) ); // false
console.log( hasOwnConstructor(ins2) ); // true
误报仍然有可能,但正则表达式使检查相当严格,因此不太合理。
关于JavaScript:如何检测ES6类有自己的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46123790/