面向对象的语言的特性:封装、继承、多态
一、ES5继承
- 借助原型链实现继承
function Parent() {
this.name = 'parent';
}
function Child() {
this.type = 'child';
}
Parent.prototype.show = function () {
console.log('parent的show方法')
}
//prototype是子类的构造函数的原型对象的一个属性,给他赋值一个父类的实例对象
Child.prototype = new Parent();
let obj = new Child();
console.log(obj.name); //parent
obj.show(); //parent的show方法
借助原型链可以继承父级原型链上的方法
二、ES6继承(extends)
在ES6中,Class之间可以通过extends关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多。
class Parent {
constructor() {
this.age = 18
}
}
class Child extends Parent {
constructor() {
super(); //必须在this之前
this.name = "zhangsan";
}
}
let parent = new Parent();
let child = new Child();
console.log(parent.age) //18
console.log(child.age) //18










网友评论