js继承

256 阅读1分钟

组合继承

function Person(name) {
    this.name = name;
}
Person.prototype.alertName = function () {
    alert(this.name);
}
function Child(name, age) {
    Person.call(this, name);// 对象冒充继承:无法继承原型链上的属性和方法
    this.age = age;
}
// 原型链继承:原型链和构造函数中的属性和方法都可以继承,但是无法传参
// Child.prototype = new Person();
Child.prototype = Object.create(Person.prototype,{
    constructor: {
        value: Child,
        enumerable: false,
        writable: true,
        configurable: true
    }
});
let child1 = new Child('zs',18);

Class继承

class Person{
    constructor(name){
        this.name = name;
    }
    alertName(){
        alert(this.name);
    }
}
class Child extends Person{
    constructor(name,age){
        super(name);
        this.age = age;
    }
}
let child1 = new Child('zs',18);

js中并不存在类,class只是语法糖,其本质还是函数。

typeof Person // "function"
Person instanceof Function // true