如何重写一个方法,并且仍然能够在重写的方法中使用基方法
How to override a method and still be able to use the base method in the overridden one
我有这个代码
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()
};
相关文章:
- 如何重写一个方法,并且仍然能够在重写的方法中使用基方法
- 将其中一个异步方法重写为使用promise的方法
- 在类外重写Javascript方法,使用默认行为
- setStyleClass方法正在重写已定义的styleClass
- 重写jQuery插件方法
- 用函数重写reduce方法
- 重写JavaScript中的Object.create方法
- 如何重写这段代码,使执行不必从Javascript Promise.then()方法开始
- 对于EmberJs模型,为什么不建议重写“init”方法
- 重写javascript方法enable
- Mootools 类扩展了调用重写的父方法
- 如何重写特定数组的方法
- ES6 重写父方法
- 调用原型的重写方法,然后调用下一个原型的重写方法错误
- 在主干模型中重写 fetch() 方法
- 恢复“重写”窗口方法
- jQuery's的CSS方法重写:hover属性
- 方法重写不能正常工作
- JavaScript中的类/实例方法重写
- 我如何使用以下方法重写它...否则条款