类的设计模式:实例化、继承和(相对)多态。设计模式
JavaScript经过原型链,在两个对象之间建立一个关联。这样,一个对象就能够经过委托访问另外一个对象的属性和函数,从而达到“继承”的实现。app
下面来看一个例子:函数
function Foo(name) { this.name = name; } Foo.prototype.myName = function () { return this.name; }; function Bar(name, label) { Foo.call(this, name); this.label = label; } Bar.prototype = new Foo(); //实现prototype的关联 Bar.prototype.myLabel = function () { return this.label; }; var a = new Bar("a", "obj a"); a.myName(); // "a" a.myLabel(); // "obj a"
每一个函数都有一个prototype属性,函数的prototype属性指向了一个对象,这个对象正是调用该构造函数而建立的实例的原型。例子中Bar.prototype就是实例a的原型。this
这是每个JavaScript对象(除了 null )都具备的一个属性,叫__proto__,这个属性会指向该对象的原型。spa
a.__proto__ === Bar.prototype //true Bar.prototype.__proto__ === Foo.prototype //true
constructor,每一个原型都有一个 constructor 属性指向关联的构造函数。prototype
Foo === Foo.prototype.constructor
function objectFactory() { var obj = new Object(),Constructor = [].shift.call(arguments); obj.__proto__ = Constructor.prototype; var ret = Constructor.apply(obj, arguments); return typeof ret === 'object' ? ret : obj; };
下面介绍,另外两种写法:设计
var Foo = { init: function(name){ this.name = name; }, myName: function(){ return this.name; } }; var Bar = Object.create(Foo); Bar.setup = function(name, label){ // 委托调用 this.init(name); this.label = label; }; Bar.myLabel = function(){ return this.label; }; var a = Object.create( Bar ); a.setup("a", "obj a"); a.myName(); // "a" a.myLabel(); // "obj a"
Object.create = function (o) { var F = function () {}; F.prototype = o; return new F(); };
class Foo { constructor(name) { this.name = name; } myName() { return this.name; } } class Bar extends Foo { constructor(props, label) { super(props); this.label = label; } myLabel() { return this.label; } } var a = new Bar("a", "obj a"); a.myName(); // "a" a.myLabel(); // "obj a"