千家信息网

什么是javascript uber

发表于:2024-10-25 作者:千家信息网编辑
千家信息网最后更新 2024年10月25日,本篇内容介绍了"什么是javascript uber"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!j
千家信息网最后更新 2024年10月25日什么是javascript uber

本篇内容介绍了"什么是javascript uber"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

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 helperfunction extend(Child, Parent) {  var F = function () {};  F.prototype = Parent.prototype;  Child.prototype = new F();  Child.prototype.constructor = Child;  Child.uber = Parent.prototype;}// define -> augmentfunction Shape() {}Shape.prototype.name = 'Shape';Shape.prototype.toString = function () {  return this.constructor.uber  ? this.constructor.uber.toString() + ', ' + this.name  : this.name;};// define -> inherit -> augmentfunction TwoDShape() {}extend(TwoDShape, Shape);TwoDShape.prototype.name = '2D shape';// definefunction Triangle(side, height) {  this.side = side;  this.height = height;}// inheritextend(Triangle, TwoDShape);// augmentTriangle.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 uber"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

0