實現原理:在子類的構造函數中調用父類的構造函數。app
function Parent(name){ this.name = name; this.age = 40; this.sayName = function(){ console.log(this.name); } this.sayAge = function(){ console.log(this.age); } } function Child(name){ this.parent = Parent; this.parent(name); delete this.parent; this.saySomething = function(){ console.log(this.name); this.sayAge(); } } var child = new Child('Lee'); child.saySomething(); //Lee //40
實現原理:使用call方法改變函數上下文this指向,使之傳入具體的函數對象。函數
function Parent(name){ this.name = name; this.age = 40; this.say = function(){ console.log(this.name + this.age); } } function Child(name){ Parent.call(this,name); } var child = new Child('Mike'); child.say();//Mike40
實現原理:使用apply方法改變函數上下文this指向,使之傳入具體的函數對象。this
function Parent(name){ this.name = name; this.age = 40; this.say = function(){ console.log(this.name + this.age); } } function Child(name){ Parent.apply(this,[name]); //Parent.apply(this,arguments); 效果同上 } var child = new Child('Wade'); child.say();//wade40
實現原理:子類的原型對象指向父類的實例,即重寫類的原型。prototype
function Parent(name){ this.name = name; this.say = function(){ console.log(this.name +' '+ this.age); } } function Child(age){ this.age = age; this.saySomething = function(){ console.log(this.name); } } Child.prototype = new Parent('petter'); var child = new Child(20); child.say();//petter 20
實現原理:使用原型鏈實現對原型屬性和方法的繼承,而經過借用構造函數來實現對實例屬性的繼承。code
function Parent(age){ this.name = 'petter'; this.age = age; } Parent.prototype.say = function(){ return this.name + ' ' + this.age; } function Child(age){ Parent.call(this,age); //Parent.apply(this,[age]); this.age = age; } Child.prototype = new Parent(); var child = new Child(21); child.say();//petter 21
實現原理:經過寄生方式,砍掉父類的實例屬性,這樣,在調用兩次父類的構造的時候,就不會初始化兩次實例方法/屬性,避免的混合繼承的缺點對象
function Animal(name){ this.name = name; this.sleep = function(){ console.log(this.name + 'is sleeping'); } } function Cat(name){ Animal.call(this); this.name = name || 'Tom'; } (function(){ // 建立一個沒有實例方法的類 var Super = function(){}; Super.prototype = Animal.prototype; //將實例做爲子類的原型 Cat.prototype = new Super(); })(); // Test Code var cat = new Cat(); console.log(cat.name);//Tom console.log(cat.sleep());//Tom is sleeping console.log(cat instanceof Animal); // true console.log(cat instanceof Cat); //true
因爲此篇中有涉及原型鏈和Call、Apply, 後面會寫關於此知識點的文章。繼承