0

我需要重写一个方法并在重写的方法中使用基方法。

到目前为止我想出了这个

http://jsfiddle.net/tyR8Q/

但我想知道这是否是解决这个问题的最佳方法。

4

1 回答 1

1

关键是使用函数的应用方法。

这是我的解决方案:

function Super(x){this.x = x}
Super.prototype.method = function(y){console.log("Super " + this.x + y)}

function Sub(x){Super.apply(this, arguments)}
Sub.prototype = Object.create(Super.prototype)
Sub.prototype.constructor = Sub
Sub.prototype.method = function(y){
  Super.prototype.method.apply(this, arguments)
}

var sub = new Sub(1)
sub.method(2)

我试图尽可能地遵循标准,在构造函数中定义类的字段,在原型中定义方法,并为子类创建一个新函数。

注意我调用了超类的构造函数和方法。

于 2015-05-24T14:06:25.040 回答