JS利用原型链实现继承
原型链继承:一个构造函数的原型是另一个类型的实例,那么这个构造函数new出来的实例就具有该实例的属性和方法
function Person(){this.flag = truethis.info={age:18,name:'张三'}}Person.prototype.getInfo = function(){console.log(this.info)console.log(this.flag)}function Child(){}Child.prototype = new Person()let child1 = new Child()child1.info.gender = '男'child1.getInfo()//{age: 18, name: '张三', gender: '男'} true
再来个简单的例子
function Animal() {}
Animal.prototype.eat = function () {console.log("Animal eats");
};function Dog() {}
Dog.prototype = new Animal(); // 原型链继承const dog = new Dog();
dog.eat(); // 输出:Animal eats