繼承是一種減小重複性代碼的一種設計模式,儘可能弱化對象間耦合,開閉原則的一種很好的實現。javascript
因爲javascript的語言特性,它的繼承也被分爲了3中實現方式java
function extend(subClass, superClass) { var F = function () { }; F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass; subClass.superclass = superClass.prototype; if (superClass.prototype.constructor == Object.prototype.constructor) { superClass.prototype.constructor = superClass; } } function Person(name) { this.name = name; } Person.prototype.getName = function () { return this.name; } function Author(name, books) { Author.superclass.constructor.call(this, name); this.books = books; } extend(Author, Person); Author.prototype.getBooks = function () { return this.books; }; Author.prototype.getName = function () { var name = Author.superclass.getName.call(this); return name + ', Author of ' + this.getBooks().join(', '); }; var hugo = new Author('hugo', ['Notre-Dame de Paris']); hugo.getName(); hugo.getBooks();
這種繼承方式比較適合不熟悉javascript語言原型的程序員使用。程序員
function clone(object) { function F() { } F.prototype = object; return new F; } var Person = { name: '默認值', getName: function () { return this.name; } } var Author = clone(Person); Author.books = []; // Default value. Author.getBooks = function() { return this.books; } hugo = clone(Author); hugo.name = 'hugo'; hugo.books =['Notre-Dame de Paris']; hugo.getName(); hugo.getBooks();
這種繼承比較節約內存。可是理解更加複雜。起屬性默認值指向父類屬性。設計模式
function augment(receivingClass, givingClass) { if(arguments[2]) { // Only give certain methods. for(var i = 2, len = arguments.length; i < len; i++) { receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]]; } } else { // Give all methods. for(methodName in givingClass.prototype) { if(!receivingClass.prototype[methodName]) { receivingClass.prototype[methodName] = givingClass.prototype[methodName]; } } } } var Mixin = function() {}; Mixin.prototype = { serialize: function() { var output = []; for(key in this) { output.push(key + ': ' + this[key]); } return output.join(', '); } }; function Person(name) { this.name = name; } Person.prototype.getName = function () { return this.name; } augment(Person, Mixin,'serialize'); var hugo = new Person('hugo'); hugo.serialize();
這種繼承方式是爲了擴充類的一些重複函數而不重寫代碼,這個也是一種多繼承的效果。函數
javascript的繼承大致上使用原型的方式會比較節省內存空間,不過也有必定的使用難度。不過在理解了原型之後就能夠這是一種很是簡化的繼承方式,對於擴展也很方便。因此在使用javascript的繼承前,最好能夠很好的理解下原型鏈這個概念。this