1

我有这个代码

function test(){};

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

var t = new test();
t.testMethod();

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

4

2 回答 2

1

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

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/

于 2012-09-08T18:17:39.850 回答
0

您可以像这样在测试原型上使用旧方法的引用:

function test(){};

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

function test2(){};

test2.prototype = new test();

test2.prototype.testMethod = function(){
  return test.prototype.testMethod()
};
于 2012-09-08T18:12:34.473 回答