看《JavaScript 设计模式》,关于里面提到的JS继承实现的方式,分为三种,且书中都给出了相关实现。这里也不再做讲解,只求记录一下,因为自己总是有时候会忘记这些东西。
- 类式继承,extend
- 原型式继承,clone
- 掺元类继承,augment
类式继承的实现,这里面很有必要引人注意的是,superclass.prototype.constructor = superclass; 而且实现空实例要省很多资源。
如果还想调用类里面的方法,而非其原型对象的方法,可以使用call函数或者apply函数,这里不再缀述。
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 ;
}
}
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 clone
(object
)
{
function F ( ) { }
F. prototype = object ;
return new F ;
}
function F ( ) { }
F. prototype = object ;
return new F ;
}
掺元类的方式适用于那些子类与父类之间关系不大,只是单纯的想通过子类调用其父类的方法,把有用的方法继承过来。
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 ] ;
}
}
}
}
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 ] ;
}
}
}
}
// 例子
- function Author(){}
- Author.prototype = {
- 'nationality' : 'China',
- 'name' : 'Jack',
- 'gender' : 'male',
- 'mail' : 'topcss@gamil.com'
- }
- // 让Author对象继承Mixin对象的serialize方法
- augment(Author, Mixin, 'serialize');
- console.info(new Author().serialize());