javascript uber是早期javascript中用于讓某方法調(diào)用父類的一種方法,uber方法類似于Java的super。
本文操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版,DELL G3電腦。
javascript uber是什么?
在早期的JavaScript中,uber方法類似于Java的super,它可以讓某方法調(diào)用父類的方法。Douglas Crockford使用了德語的"über",其意思類似于super,避免了和保留字的沖突。
但是,Crockford也說,super的思想在classical設(shè)計(jì)模式中很重要,但是在JavaScript的原型和函數(shù)設(shè)計(jì)模式中,顯得沒有必要。Classical Inheritance in JavaScript經(jīng)典的面向?qū)ο笳Z言一般都有訪問父類(超類)的特殊語法,這樣子類的方法就可以使用父類的方法了,子類和父類的方法同名。現(xiàn)代JavaScript中,沒有這種特殊語法,uber可以實(shí)現(xiàn)這一功能,但是繁瑣一些。來看下面的例子:
// 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
函數(shù)extend將繼承的代碼封裝了起來。
臨時(shí)構(gòu)造函數(shù)F()的作用:當(dāng)子類的屬性改變時(shí),不改變父類的屬性。
uber屬性:指向父類原型。
toString()方法中,檢查構(gòu)造函數(shù)的父類的原型是否存在,如果存在,則調(diào)用其toString()方法,由此實(shí)現(xiàn)了在子類中調(diào)用父類方法。
推薦學(xué)習(xí):《javascript基礎(chǔ)教程》