js 原型与原型链继承的关系有点没懂
class Person{
}
class Child extends Person{ xxx(){
}
} class 中 方法是绑定在该类的原型上 Person 是 Child 的原型 为啥 Person 实例化对象无法调用 Child 上的 XXX 方法 有哪个大佬解释一下 感觉是我没弄懂 继承的问题。。。
class Person{
}
class Child extends Person{ xxx(){
}
} class 中 方法是绑定在该类的原型上 Person 是 Child 的原型 为啥 Person 实例化对象无法调用 Child 上的 XXX 方法 有哪个大佬解释一下 感觉是我没弄懂 继承的问题。。。
class Child extends Person{
test2(params) {
console.log(222);
}
}
var c = new Child();
c.test2();
c.test1();
这样是没问题的
> Child.prototype.hasOwnProperty(‘test’)
True
> let aChild = new Child()
> aChild.__proto__ === Child.prototype
True
> aChild.__proto__.__proto__ === Person.prototype
True
这才是这根原型链的本来面貌,更具体的,对 Person 的实例化对象而言
> let aPerson = new Person()
> aPerson.__proto__ === Person.prototype
True
aPerson 的原型链中跳过了一个环节,将 Child.prototype 跳过了,从而 aPerson 中的原型链中不可能有 test 方法。
扩展阅读
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain