js 原型链继承

构造函数的prototype__proto__默认指向Object.prototype,是继承Object

function Animal(age){
    this.age = age
}

Animal.prototype.getAge = function(){
    return this.age + ", getAge, prototype"
}

Animal.prototype.eat = function(){
    return this.age + ", eat, prototype"
}

function Dog(name, age) {
    Animal.call(this, age);
    this.name = name;
}

Dog.prototype.__proto__ = Animal.prototype;

Dog.prototype.getAge = function () {
    return this.age + ", dog, prototype"
}

let d1 = new Dog('d1', 12)
console.log(d1.getAge())
console.log(d1.eat())
console.log(Dog.prototype.constructor === d1.__proto__.constructor)

所有构造函数的原型都指向Function.prototype,因为构造函数是函数。所有原型指向继承的原型,原型是对象,所以Function.prototype的原型指向Object.prototype

Dog继承Animal继承Object

js 原型链继承_第1张图片

你可能感兴趣的:(js)