我有以下代码:
class MotherClass {
constructor(name) {
this.name = name;
}
}
class ChildClass extends MotherClass {
constructor(name, age) {
super(name);
this.age = age;
}
}
function myFunction(param1) {
//do something
}
我如何在myFunction中检查param1
是一个MotherClass(或一个扩展MotherClass的类的实例)?
答案 0 :(得分:2)
使用instanceof运算符
class MotherClass {
constructor(name) {
this.name = name;
}
}
class ChildClass extends MotherClass {
constructor(name, age) {
super(name);
this.age = age;
}
}
function myFunction(param1) {
//do something
console.log(param1 instanceof MotherClass);
}
myFunction(new ChildClass("bla", "bla"));
答案 1 :(得分:1)
@iccthedral答案将满足您的需求。
另外,请注意instanceof
因为他有时会产生会导致你误入歧途的结果。
function foo() {};
var bar = { a: "a"};
foo.prototype = bar; // Object {a: "a"}
baz = Object.create(bar); // Object {a: "a"}
baz instanceof foo // true. oops.