1. ES6
/* 此时的Child上只有name属性,没有age属性 */
<script>
// 父
class Parent{
constructor(){
this.age = 18;
}
}
// 子
class Child{
constructor(){
this.name = '张三';
}
}
let o1 = new Child();
console.log(o1, o1.name, o1.age); // 打印出:Child {name: '张三'} '张三' undefined
</script>
/* 此时的Child上既有name属性,又有age属性 */
<script>
// 父
class Parent{
constructor(){
this.age = 18;
}
}
// 子
class Child extends Parent{
constructor(){
super();
this.name = '张三';
}
}
let o1 = new Child();
console.log(o1, o1.name, o1.age); // 打印出:Child {age: 18, name: '张三'} '张三' 18
</script>
2. 原型链继承
<script>
// 父
function Parent() {
this.age = 20;
}
// 子
function Child() {
this.name = '李四';
}
Child.prototype = new Parent()
let o1 = new Child();
console.log(o1, o1.name, o1.age); // 打印出:Child {name: '李四'} '李四' 20
</script>
3. 借用构造函数继承
<script>
// 父
function Parent(){
this.age = 22;
}
// 子
function Child(){
this.name = 'xiongxinyu';
Parent.call(this); // 改变this指向
}
let o3 = new Child();
console.log(o3,o3.name,o3.age); // 打印出:Child {name: 'xiongxinyu', age: 22} 'xiongxinyu' 22
</script>
4. 组合式继承
<script>
// 父
function Parent(){
this.age = '24'
}
// 子
function Child(){
Parent.call(this)
this.name = 'y'
}
Child.prototype = new Parent();
var o4 = new Child();
console.log(o4,o4.name,o4.age); // 打印出:Child {age: '24', name: 'y'} 'y' '24'
</script>