从子对象中访问父对象。
经典的面向对象语言都有语法可以在子类中访问父类,其实就是可以直接调用父类的引用。有的时候,我们在子类写一个方法,需要用到父类的方法时候,这个特性就格外有用了。在许多应用中,子类创建一个和父类相同的方法,并且在这个方法中调用父类的方法。在Javascript中并没有这个这种语法。但是很容易就能完成这个功能,让我们看如下的代码。
function Shape(){} Shape.prototype.name = 'shape'; Shape.prototype.toString = function(){ var result = []; if (this.constructor.uber) { result[result.length] = this.constructor.uber.toString(); } result[result.length] = this.name; return result.join(', '); }; function TwoDShape(){} var F = function(){}; F.prototype = Shape.prototype; TwoDShape.prototype = new F(); TwoDShape.prototype.constructor = TwoDShape; TwoDShape.uber = Shape.prototype; TwoDShape.prototype.name = '2D shape'; function Triangle(side, height) { this.side = side; this.height = height; } var F = function(){}; F.prototype = TwoDShape.prototype; Triangle.prototype = new F(); Triangle.prototype.constructor = Triangle; Triangle.uber = TwoDShape.prototype; Triangle.prototype.name = 'Triangle'; Triangle.prototype.getArea = function(){return this.side * this.height / 2;}
新的不同在于
1.用uber的属性指向了父的prototype.
2.toString方法重写。
前一个例子中,toString方法返回了this.name,这个例子中首先检查this.constructor是否存在,存在的话就调用toString.this.constructor是函数自己本身。而this.constructor.uber指向了父的prototype.结果就是当调用Triangle实例的toString方法,所有的prototype链上的toString方法都被调用了。
var my = new Triangle(5, 10); my.toString();//"shape, 2D shape, Triangle"
不要把uber并不是所谓的父类,意思就是不像其他面向语言的super或base之类的。