汉语解释:泛指把前人的做风、文化、知识等接受过来
计算机术语解释:继承可使得子类具备父类的属性和方法或者从新定义、追加属性和方法等函数
function Animal(name) { this.name = name || 'animal'; this.speak = function () { console.log('speak'); } } Animal.prototype.move = function () { console.log('move'); }
function Cat() { this.getName = function () { console.log(this.name); }; } Cat.prototype = new Animal('cat1'); var cat = new Cat(); cat.name = 'cat2'; console.log(cat);//该实例对象有一个name为cat2,原型上有一个name是cat1 cat.getName();//cat2(先找当前属性,再找原型) console.log(cat instanceof Cat);//true console.log(cat instanceof Animal);//true
父子之间存在关系,但子类并不会建立新的属性,set子类属性并不会覆盖原型上的属性,get属性只不过是根据先读取当前属性再读取原型的优先级
function Dog(name) { Animal.call(this); this.name = name || 'doggy'; } var dog = new Dog(); console.log(dog);//只有子类属性 console.log(dog instanceof Dog); // true console.log(dog instanceof Animal); // false
实际上只是利用父类构造函数来添加子类属性,父子之间没有什么关系
class Animal2 { constructor(name) { this.name = name || 'animal2'; this.speak = function () { console.log('speak'); } } } Animal2.prototype.move = function () { console.log('move'); } var animal2 = new Animal2('god2'); console.log(animal2); class Bird extends Animal2 { getName() { console.log(this.name); } } var bird = new Bird('bird'); console.log(bird);//既有父类的属性,原型链也指向父类 bird.getName(); console.log(bird instanceof Bird); // true console.log(bird instanceof Animal2); // true