javascript uber是早期javascript中用于讓某方法調用父類的一種方法,uber方法類似于Java的super。
本文操作環境:windows7系統、javascript1.8.5版,DELL G3電腦。
javascript uber是什么?
在早期的JavaScript中,uber方法類似于Java的super,它可以讓某方法調用父類的方法。Douglas Crockford使用了德語的"über",其意思類似于super,避免了和保留字的沖突。
但是,Crockford也說,super的思想在classical設計模式中很重要,但是在JavaScript的原型和函數設計模式中,顯得沒有必要。Classical Inheritance in JavaScript經典的面向對象語言一般都有訪問父類(超類)的特殊語法,這樣子類的方法就可以使用父類的方法了,子類和父類的方法同名。現代JavaScript中,沒有這種特殊語法,uber可以實現這一功能,但是繁瑣一些。來看下面的例子:
// inheritance helper function extend(Child, Parent) { var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.uber = Parent.prototype; } // define -> augment function Shape() {} Shape.prototype.name = 'Shape'; Shape.prototype.toString = function () { return this.constructor.uber ? this.constructor.uber.toString() + ', ' + this.name : this.name; }; // define -> inherit -> augment function TwoDShape() {} extend(TwoDShape, Shape); TwoDShape.prototype.name = '2D shape'; // define function Triangle(side, height) { this.side = side; this.height = height; } // inherit extend(Triangle, TwoDShape); // augment Triangle.prototype.name = 'Triangle'; Triangle.prototype.getArea = function () { return this.side * this.height / 2; };
在Console中輸入:
var my = new Triangle(5, 10); my.toString();
輸出:"Shape, 2D shape, Triangle"
派生的層次是:Shape -> TwoDShape -> Triangle
函數extend將繼承的代碼封裝了起來。
臨時構造函數F()的作用:當子類的屬性改變時,不改變父類的屬性。
uber屬性:指向父類原型。
toString()方法中,檢查構造函數的父類的原型是否存在,如果存在,則調用其toString()方法,由此實現了在子類中調用父類方法。
推薦學習:《javascript基礎教程》