Javascript实现困境:寻找具有方法覆盖解决方案的类

Javascript implementation dilemna: looking for a class with method overriding solution

本文关键字:覆盖 解决方案 有方法 实现 困境 寻找 Javascript      更新时间:2023-09-26

我不是Javascript专家。我已经开发了一个操作页面,使用一个函数为我的一些JS代码定义一个类(如这里所述)。这个类非常复杂,可以帮助计算对象位置。它现在已经过测试并可运行。

我正在写新的页面,我想重用这个类。但是,对于每个页面,该类的至少一个方法应该被重写(就像在Java中一样)。我在另一个SO问题上读到,在Javascript中不可能重写方法。

我正在考虑修改类原型,但是如果我这样做,所有的类实例都将被修改。

我非常不愿意为每个页面复制我的类代码。对于这个问题是否有一个好的/优雅的解决方案?谢谢。

<

解决方案/strong>

因此,考虑Šime Vidas对Adam Rackis的解决方案的评论:

function Base(){}
Base.prototype.foo = function() { alert("base"); };
function Derived() {}
Derived.prototype = Object.create( Base.prototype );
Derived.prototype.foo = function() { alert("overridden"); };

var b = new Base();
var d = new Derived();
b.foo();
d.foo();

见:http://jsfiddle.net/8Gq7C/

可以在javascript中重载函数。创建一个新的函数构造函数,该构造函数继承于拥有你想要重载的方法的函数,然后在派生函数的原型上更改方法。

它看起来像这样:

function Base(){}
Base.prototype.foo = function() { alert("base"); };
function Derived() {}
//Derived.prototype = new Base(); //not ideal - see the comments
Derived.prototype = Object.create(Base.prototype); //grab MDN shim for older IE
Derived.prototype.constructor = Derived;
Derived.prototype.foo = function() { alert("overridden"); };
var b = new Base();
var d = new Derived();
b.foo();
d.foo();

现场演示