首頁  >  文章  >  web前端  >  javascript uber是什麼

javascript uber是什麼

藏色散人
藏色散人原創
2021-11-01 15:31:481535瀏覽

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基礎教學

以上是javascript uber是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn