是否有可能检测父方法是否被覆盖?

时间:2013-12-16 19:46:49

标签: javascript object javascript-objects prototypal-inheritance method-overriding

考虑这段代码:

function Parent(){};
Parent.prototype.myMethod = function()
{
    return "hi!";
}

function Child(){};
Child.prototype = Object.create(new Parent());

var objChild = new Child();

//no override...
var output = objChild.myMethod();
alert(output); // "hi!"


//override and detect that in Parent.myMethod()
Child.prototype.myMethod = function()
{
    var output = Parent.prototype.myMethod.call(this);

    alert("override: " + output); // "hi!"    
};
objChild.myMethod();

是否可以“自然地”或通过“覆盖”确定Parent.myMethod()是否被调用,并且在这种情况下返回其他内容?

DEMO

2 个答案:

答案 0 :(得分:1)

  

是否可以“自然地”或通过“覆盖”

来确定是Parent.myMethod()

不是真的(不使用非标准,已弃用的caller property)。但是,您可以检测何时在具有不同myMethod属性的对象上调用方法:

this.myMethod === Parent.prototype.myMethod
  

并且在那种情况下返回别的东西?

你真的不应该。使它成为您期望别的东西的参数(but beware),或者用两种不同的方法划分功能。

答案 1 :(得分:0)

在我看来,你不要覆盖这个方法,方法是将this传递给你调用函数的调用函数,就像它是Child的函数一样,你可以即使你没有从Parent继承,也要这样做。