什么是继续
继续是一种削减反复性代码的一种设想形式,只管弱化对象间耦合,开闭准绳的一种很好的完成。
javascript继续
因为javascript的言语特征,它的继续也被分为了3中完成体式格局
一、类继续
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的继续前,最好能够很好的明白下原型链这个观点。