如何重写一个方法,并且仍然能够在重写的方法中使用基方法

How to override a method and still be able to use the base method in the overridden one

本文关键字:方法 重写 何重写 一个      更新时间:2023-09-26

我有这个代码

function test(){};
test.prototype.testMethod = function(){return 1;}
var t = new test();
t.testMethod();

现在我需要重写方法testMethod,这样我仍然可以在重写中调用基方法。我如何使用原型来做到这一点?

如果您需要覆盖单个实例的基本方法,您仍然可以引用原型中定义的方法:

function test(){};
test.prototype.testMethod = function() {console.log('testMethod in prototype');}
var t = new test();
t.testMethod = function () {
    console.log(this);
    console.log('testMethod override');
    test.prototype.testMethod();    
};
t.testMethod();

试试看:http://jsfiddle.net/aeBWS/

如果你想替换原型方法本身,你有几个途径。最简单的方法就是为函数选择一个不同的名称。如果这不可能,那么您可以将旧方法复制到一个具有新名称(如_testMethod)的方法中,并以这种方式调用它:

function test(){};
test.prototype.testMethod = function() {console.log('testMethod in prototype');}  
test.prototype._oldTestMethod = test.prototype.testMethod;
test.prototype.testMethod = function() {
    console.log('testMethod override');
    test.prototype._oldTestMethod ();    
};
var t = new test();
t.testMethod();

试试看:http://jsfiddle.net/x4txH/

您可以在测试原型上使用旧方法的引用,如下所示:

function test(){};
test.prototype.testMethod = function(){
  return 1;
}
function test2(){};
test2.prototype = new test();
test2.prototype.testMethod = function(){
  return test.prototype.testMethod()
};