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

我在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); } 

另一种方法是使用以下方法来inheritance类:

 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) // eg 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(); }; })(); 

这样就没有依赖于你从Baseinheritance。

附注:您正在寻找的术语是“重写”基本方法。