本文所有继承方法均是ES5及以下,ES6extends
继承请看。
缺点:
function Animal(type, name) { //父类 this.type = type; this.name = name; } Animal.prototype.Foraging = function () { //父类方法 console.log("eating..."); } function Dog(name, age) { //子类 this.name = name; this.age = age; } Dog.prototype = Animal.prototype;//继承核心 Dog.prototype.say = function () { //子类方法 console.log("bark....") } let dog = new Dog("Tim", 3); dog.Foraging(); //eating... console.log(Animal.prototype) //say: ƒ ()
通过将子类的原型指向了父类,因此子类将父类的所有属性和方法都作为自己共有的属性和方法。
缺点:
function Animal(type, name) { this.type = type; this.name = name; this.sleep = function () { console.log("sleep..."); } } Animal.prototype.Foraging = function () { console.log("eating..."); } function Dog(type, name, age) { Animal.call(this, type, name); //继承核心 this.age = age; } Dog.prototype.say = function () { console.log("bark...") } let dog = new Dog("dog", "Tim", 3); dog.sleep(); //sleep... // dog.Foraging();//is not a function dog.say()//bark...
使用call
方法,将父元素的this
改为调用者。
缺点:
function Animal(type, name) { this.type = type; this.name = name; } Animal.prototype.Foraging = function () { console.log("eating..."); } function Dog(type, name, age) { Animal.call(this, type, name); //继承核心1 this.age = age; } Dog.prototype = new Animal(); //继承核心2 Dog.prototype.say = function () { console.log("bark...") } let dog = new Dog("dog", "Tim", 3); dog.Foraging();//eating... dog.say() //bark... console.log(Animal.prototype)//没有say方法
使用call
方法继承父类属性,使用原型链继承父类共有方法。
function Animal(type, name) { this.type = type; this.name = name; } Animal.prototype.Foraging = function () { console.log("eating..."); } function Dog(type, name, age) { Animal.call(this, type, name); this.age = age; } function extend(chlid, parent) { //封装继承核心 function Fn() { } Fn.prototype = parent.prototype; chlid.prototype = new Fn(); } extend(Dog, Animal); //继承核心 Dog.prototype.say = function () { console.log("bark....") } let dog = new Dog("dog", "Tim", 3); dog.Foraging();//eating... dog.say()//bark... console.log(Animal.prototype)//没有say方法