例如:
class Parent {
foo() {
console.log("foo");
}
}
class Child extends Parent {
bar() {
console.log("bar");
}
}
这里,表达式
Object.getPrototypeOf(Child) === Parent
将判断为true.
现在我了解了原型继承的基本知识以及类在Javascript中的工作方式,也就是说,每个函数都有一个prototype
属性,在使用new
操作符调用该函数时,该属性会复制到新创建的类实例的__proto__
属性中
我还理解,Object.getPrototypeOf
基本上返回任何给定对象的__proto__
属性,通常我们通过将子类的prototype
属性设置为父类的实例来模拟纯javascript中的继承,如下所示:
function Parent(){}
Parent.prototype.foo = function(){
console.log("foo");
}
function Child(){}
// Inherit properties from Parent
Child.prototype = new Parent();
我的问题是:
-
用类作为参数调用
Object.getPrototypeOf
的结果代表什么?它是如何与TS/JS中的类继承联系在一起的? -
使用
Object.getPrototypeOf
判断特定类是否在运行时扩展了另一个类是否安全?