简体   繁体   English

调用阴影原型方法的更简单/更好的方法?

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

I'm writing an object hierarchy in JavaScript, I would like to call a method on an object's parent when I've shadowed that method in the object. 我在JavaScript中编写一个对象层次结构,当我在对象中隐藏该方法时,我想在对象的父对象上调用一个方法。

Eg: 例如:

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();

See the three lines at the bottom of the Sub.prototype.log function - is there a better way to do what I'm trying to do there? 看看Sub.prototype.log函数底部的Sub.prototype.log - 有没有更好的方法来做我想做的事情?

The second line is the best I've been able to come up with but is very verbose! 第二行是我能够提出的最好的,但是非常冗长!

super is not defined, obviously it wouldn't work. super没有定义,显然它不会起作用。

You might want to try: 您可能想尝试:

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

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

Another way is to use the following method to inherit classes: 另一种方法是使用以下方法继承类:

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;      
}

So here is an example: 所以这是一个例子:

// ..
extend(Sub, Base);

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

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

In case of ES6 : 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();

If you want to keep the original method without using the name Base you could capture it using a closure before you change it. 如果要在不使用名称Base情况下保留原始方法,则可以在更改之前使用闭包捕获它。

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

This way there is no dependancy on how you inherit from Base . 这样就没有依赖于你如何从Base继承。

Side note: the terminology you are looking for is 'overriding' the base method. 旁注:您正在寻找的术语是“覆盖”基本方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM