您可以在没有任何额外库的情况下做到这一点 - 只是有点冗长。
jsFiddle
首先建立一个car类并给它一些方法(setColor、setMake和setModel):
function car(make,model){
console.log( 'car constructor' );
this.setMake( make );
this.setModel( model );
}
car.prototype.setColor = function(color){ this.color = color; };
car.prototype.setMake = function(make ){ this.make = make; };
car.prototype.setModel = function(model){ this.model = model; };
car.prototype.toString = function(){ return 'This is a ' + this.color + ' ' + this.make + ' ' + this.model + ' car' };
那么你可以从汽车继承:
function volvo( model ){
console.log( 'volvo constructor' );
car.call( this, 'volvo', model );
}
volvo.prototype = Object.create( car.prototype );
volvo.prototype.constructor = volvo;
然后查看各个部分:
-
function volvo( model ){} 定义了一个 volvo 类。
- 并且在构造函数中
car.call( this, 'volvo', model ); 用于调用固定make 为volvo 的父类的构造函数。
-
volvo.prototype = Object.create( car.prototype ); 将volvo 类设置为从car 类继承。
-
volvo.prototype.constructor = volvo; 用于确保volvo 类使用volvo 构造函数(如果没有这行,前面的语句将导致它使用car 构造函数)。
然后我们可以测试一下:
var c = new car('Ford', 'Fiesta');
c.setColor('Red');
console.log( c.toString() );
var v = new volvo( 'S10' );
v.setColor( 'Grey' );
console.log( v.toString() );
输出是(包括显示何时调用构造函数的日志条目):
car constructor
This is a Red Ford Fiesta car
volvo constructor
car constructor
This is a Grey volvo S10 car
如果您需要为 Object.create 使用 polyfill,那么您可以使用:
if (!Object.create) {
Object.create = (function(){
function F(){}
return function(o){
if (arguments.length != 1) {
throw new Error('Object.create implementation only accepts one parameter.');
}
F.prototype = o
return new F()
}
})()
}