<script>
class Parent{
constructor(){
this.age = 18;
}
}
class Child{
constructor(){
this.name = '张山';
}
}
let o1 = new Child();
console.log(o1.name,o1.age);//'张山' undefined
</script>
<script>
class Parent{
constructor(){
this.age = 18;
}
}
class Child extends Parent{
constructor(){
super();
this.name = '张山';
}
}
let o1 = new Child();
console.log(o1.name,o1.age);//'张山' 18
</script>
1、如果父类实例的属性是引用类型的时候,其实父类的实例属性会成为子类的原型属性,子类创建的所有实例都会共享这些方法,修改一个实例的这个属性,其他实例的属性也会被修改。
2、子类型在实例化时不能给父类型的构造函数传参。
<script>
function Parent(){
this.age = 18;
}
function Child(){
this.name = '张山';
}
let o1 = new Child();
console.log(o1.name,o1.age);//'张山' undefined
</script>
<script>
function Parent(){
this.age = 18;
}
function Child(){
this.name = '张山';
}
Child.prototype = new Parent();
let o1 = new Child();
console.log(o1.name,o1.age);//'张山' 18
</script>
1、只能在构造函数中调用方法 函数不能重用 就是每次子类生成实例的时候都会生成一次属性和方法。
2、子类无法访问到父类原型上的方法。
<script>
function Parent(){
this.age = 18;
}
function Child(){
this.name = '张山';
Parent.call(this);
}
let o1 = new Child();
console.log(o1.name,o1.age);//'张山' 18
</script>
调用了两次父类构造函数 比较耗内存。
<script>
function Parent(){
this.age = 18;
}
function Child(){
//借用构造函数
Parent.call(this)
this.name = '张山';
}
//原型链继承
Child.prototype = new Parent();
let o1 = new Child();
console.log(o1.name,o1.age);//'张山' 18
</script>
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务