JavaScript 是一种无类语言。类不存在,但对象可以通过使用原型从彼此继承属性。这意味着您不仅限于以类方式实现继承。就个人而言,我喜欢使用受 BackboneJS 启发的方法(代码需要 UnderscoreJS):
var BaseObject = function(){}; //Create a function so that we may use the new operator.
//There may be code in the constructor
BaseObject.extend = function(obj) { //Add a static function to the BaseObject to extend it
var base = this; //Save a reference for later
//Create the constructor for the sub object. We need to extend it, so we can't use the base constructor. AFAIK, this is the only way to clone the base constructor, i.e. by creating a new function that calls it
var SubObject = _.extend(function(){
base.apply(this, arguments); //Call base constructor
}, this);
SubObject.prototype= _.extend({}, this.prototype, obj); //Create new prototype that extends the super prototype, but does not overwrite it.
return SubObject; //Return the new constructor + prototype
};
这使您可以像这样做很酷的类类似的东西:
var Car = BaseObject.extend({
speed: 0,
acceleration: 5,
accelerate: function(){
this.speed += this.acceleration;
}
});
var RaceCar = Car.extend({
acceleration: 10,
});
var car = new Car();
var raceCar = new RaceCar();
car.accelerate();
raceCar.accelerate();
if(raceCar.speed > car.speed){
console.log('raceCar won');
}else{
console.log('car won');
}
有关 JavaScript 继承的更多信息,我强烈建议阅读 Douglas Crockford 的 JavaScript:The Good Parts。
关于你的例子:
1 和 2 之间的差异很小。有关详细信息,请参阅此问题。
在 3 中,您只是返回一个对象文字。new 关键字只对函数中的 this 关键字有影响,你没有使用它,所以使用 new 没有效果。有关更多信息,请参阅此问题