JavaScript 面向对象的范式是基于原型 http://en.wikipedia.org/wiki/Prototype-based_programming。没有“类”,只有对象。
您可以通过不同的方式实现继承。两种更流行的替代方案是“伪古典”和“原型”形式。例如:
伪经典继承
我认为这是最流行的方式。你创造构造函数 https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Creating_New_Objects/Using_a_Constructor_Function与您一起使用的new https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/new_Operator运算符,并通过构造函数原型添加成员。
// Define the Person constructor function
function Person() {}
Person.prototype.sayHello = function(){
alert ('hello');
};
// Define the Student constructor function
function Student() {}
// Inherit from Person
Student.prototype = new Person();
// Correct the constructor pointer, because it points to Person
Student.prototype.constructor = Student;
// Replace the sayHello method (a polymorphism example)
Student.prototype.sayHello = function () {
alert('hi, I am a student');
}
var student1 = new Student();
student1.sayHello();
原型继承 http://javascript.crockford.com/prototypal.html
基本上,我们创建一个辅助函数,它将一个对象作为参数并返回一个继承旧对象的空新对象,对象继承自对象.
// Helper function
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
var person = {
sayHello : function () {
alert('Person object');
},
walk : function () {
alert('walk');
}
};
var student1 = Object.create(person);
student1.sayHello = function () {
alert('hello I am a student');
};
另一种有趣的形式是寄生遗传。在“派生”构造函数中,您创建一个“基础”对象实例。该对象被增强并返回新实例:
// Person constructor function
function Person(name) {
this.name = name;
}
function Student(value) {
var that = new Person(value);
that.sayHello = function () {
alert('hello I am a student');
};
return that;
}