簡體   English   中英

調用陰影原型方法的更簡單/更好的方法?

[英]Simpler / better way to call shadowed prototype method?

我在JavaScript中編寫一個對象層次結構,當我在對象中隱藏該方法時,我想在對象的父對象上調用一個方法。

例如:

var Base = function Base(msg) {
  this.msg = msg;
}
Base.prototype.log = function(){
  console.log("base log: " + this.msg);
}

var Sub = function Sub(msg) {
  Base.call(this, msg);
}

Sub.prototype = Object.create(Base.prototype);

Sub.prototype.log = function() {
  console.log("sub log");

  this.__proto__.__proto__.log.call(this); // This works but __proto__
  Object.getPrototypeOf(Object.getPrototypeOf(this)).log.call(this); // This works but is verbose
  super.log(); // This doesn't work
}

var sub = new Sub('hi');
sub.log();

看看Sub.prototype.log函數底部的Sub.prototype.log - 有沒有更好的方法來做我想做的事情?

第二行是我能夠提出的最好的,但是非常冗長!

super沒有定義,顯然它不會起作用。

您可能想嘗試:

Sub.prototype.log = function() {
  console.log("sub log");

  Base.prototype.log.call(this);
}

另一種方法是使用以下方法繼承類:

function extend(Child, Parent) {
    var F = function() { };
    F.prototype = Parent.prototype;
    Child.prototype = new F();    

    // better to make it static (better practice in OOP world) 
    // e.g. Child.super = ...,
    // but in your case:
    Child.prototype.super = Parent.prototype;      
}

所以這是一個例子:

// ..
extend(Sub, Base);

Sub.prototype.log = function() {
  console.log("sub log");

  this.super.log.call(this);
}

ES6情況下:

class Base {
  constructor(msg) {
    this.msg = msg;
  }

  log(){
    console.log("base log: " + this.msg);
  }
}

class Sub extends Base {
  constructor(msg) {
    super(msg);
  }

  log() {
    console.log("sub log");
    super.log();
  }
}

var sub = new Sub('hi');
sub.log();

如果要在不使用名稱Base情況下保留原始方法,則可以在更改之前使用閉包捕獲它。

(function() {
   var superLog = Sub.prototype.log;
   Sub.prototype.log = function() {
       console.log("sub log");
       superLog();
   };
})();

這樣就沒有依賴於你如何從Base繼承。

旁注:您正在尋找的術語是“覆蓋”基本方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM