站长资讯网
最全最丰富的资讯网站

javascript uber是什么

javascript uber是早期javascript中用于让某方法调用父类的一种方法,uber方法类似于Java的super。

javascript uber是什么

本文操作环境: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基础教程》

赞(0)
分享到: 更多 (0)