Edit: It's now six years since the original answer was written and a lot has changed!
- If you're using a newer version of JavaScript, possibly compiled with a tool like Babel, you can use real classes.
- If you're using the class-like component constructors provided by Angular or React, you'll want to look in the docs for that framework.
- If you're using ES5 and making "fake" classes by hand using prototypes, the answer below is still as right as it ever was.
Good luck!
JavaScript inheritance looks a bit different from Java. Here is how the native JavaScript object system looks:
// Create a class
function Vehicle(color){
this.color = color;
}
// Add an instance method
Vehicle.prototype.go = function(){
return "Underway in " + this.color;
}
// Add a second class
function Car(color){
this.color = color;
}
// And declare it is a subclass of the first
Car.prototype = new Vehicle();
// Override the instance method
Car.prototype.go = function(){
return Vehicle.prototype.go.call(this) + " car"
}
// Create some instances and see the overridden behavior.
var v = new Vehicle("blue");
v.go() // "Underway in blue"
var c = new Car("red");
c.go() // "Underway in red car"
Unfortunately this is a bit ugly and it does not include a very nice way to "super": you have to manually specify which parent classes' method you want to call. As a result, there are a variety of tools to make creating classes nicer. Try looking at Prototype.js, Backbone.js, or a similar library that includes a nicer syntax for doing OOP in js.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…