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

时间:2016-04-29 05:20:23

标签: javascript node.js

我在JavaScript中编写对象层次结构,当我在对象中隐藏该方法时,我想在对象的父级上调用一个方法。

E.g:

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功能底部的三行 - 是否有更好的方法可以做我想做的事情?

第二行是我能够提出的最好的,但是非常详细!

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

如果您想在不使用名称Base的情况下保留原始方法,则可以在更改之前使用闭包捕获它。

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

这种方式不依赖于你如何从Base继承。

旁注:您正在寻找的术语是“覆盖”基本方法。