es5如何實(shí)現(xiàn)繼承
es5實(shí)現(xiàn)繼承主要是通過原型來實(shí)現(xiàn)的
- 首先實(shí)現(xiàn)一個(gè)父類
function Father(name, age){ this.name = name; this.age = age; this.work = function (){ console.log('Father is working!') } } Father.prototype.address = 'chengdu'; Father.prototype.code = function() { console.log('Father is coding!') }
- 其次實(shí)現(xiàn)一個(gè)子類繼承父類
function Child(name, age) { Father.call(this, name, age); } Child.prototype = Father.prototype;
這里面主要是兩個(gè)部分:
1.父類原型數(shù)據(jù)的繼承
Child.proptotype = Father.proptotype
2.父類非原型部分的數(shù)據(jù)的繼承
Father.call(this, name, age)
這種繼承方式叫做混合繼承
現(xiàn)在查看一個(gè)繼承類父類的子類是什么樣的:
image
es6如何實(shí)現(xiàn)繼承
通過extends就可以實(shí)現(xiàn)
class Father {
constructor(name, age){
this.name = name;
this.age = age;
}
work(){
console.log('father is working');
}
}
class Child extends Father{
constructor(name, age) {
super(name, age);
}
}
這樣子類就擁有了父類的屬性和方法了