JS 中的继承
原生JS(ES5)中的继承
对象冒充继承: 没法继承原型链上面的属性和方法
function Person(name, age) { this.name = name; this.age = age; this.run = function () { console.log(`${this.name} is ${this.age}岁`) } } Person.prototype.sex = '男' Person.prototype.work = function () { console.log(`${this.name} is ${this.sex} and ${this.age}岁`) } function Man(name, age) { Person.call(this, name, age) //对象冒充实现继承 } var man = new Man('sally', 18) man.run() man.work() /** man.work is not a function */
原型链继承:可以继承构造函数里面以及原型链上面的属性和方法,实例化子类的时候没法给父类传参
function Person(name, age) { this.name = name; this.age = age; this.run = function () { console.log(`${this.name} is ${this.age}岁`) } } Person.prototype.sex = '男' Person.prototype.work = function () { console.log(`${this.name} is ${this.sex} and ${this.age}岁`) } //原型链继承 function Man(name, age) {} Man.prototype = new Person() var man = new Man('sally', 18) man.run() man.work() /** undefined is undefined岁 undefined is 男 and undefined岁 */
采用原型链继承和对象冒充继承相结合的方式继承:
function Person(name, age) { this.name = name; this.age = age; this.run = function () { console.log(`${this.name} is ${this.age}岁`) } } Person.prototype.sex = '男' Person.prototype.work = function () { console.log(`${this.name} is ${this.sex} and ${this.age}岁`) } //对象冒充实现继承 function Man(name, age) { Person.call(this, name, age) } //原型链继承 Man.prototype = new Person() var man = new Man('sally', 18) man.run() man.work() /** * sally is 18岁 * sally is 男 and 18岁 */
ES6 中的继承
通过 extends 关键字:
class Person { constructor(name, age) { this.name = name; this.age = age; } getInfo() { console.log(`姓名:${this.name} 年龄:${this.age}`); } run() { console.log('run') } } class Man extends Person { //继承了Person extends super(name,age); constructor(name, age, sex) { super(name, age); //实例化子类的时候把子类的数据传给父类 this.sex = sex; } print() { console.log(this.sex); } } var man = new Man('jack', '30', '男'); man.getInfo(); /** * 姓名:jack 年龄:30 */