0

考虑这段代码:是否有可能检测父方法是否被覆盖?

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

+1

'Object.create(new Parent());' - 哎!它应该是Object.create(Parent.prototype); – Bergi

+0

@Bergi谢谢你的纠正!我是新的原型继承 –

+2

是否有真正的用例?如果是这样,可能会有设计问题。 –

回答

1

是否有可能以确定是否Parent.myMethod()被称为“自然”,或通过“覆盖”

没有真正(而不是诉诸于不规范,不建议使用caller property)。

this.myMethod === Parent.prototype.myMethod 

,并在这种情况下返回别的东西:但是,当调用该方法具有不同的myMethod属性的对象上,你可以检测?

你真的不应该这样做。将它作为您期望的其他参数(but beware),或者用两种不同的方法划分功能。

+0

如何进行检测?我完全不理解你,对不起! –

+0

只要if(this.myMethod === Parent.prototype.myMethod){/ *'this'对象似乎没有被覆盖的版本* /} else {/ *'this'有一个'myMethod'不是从父* /}'继承的 – Bergi

0

在我看来,你没有覆盖的方法,通过传递this到你调用该函数就像是Child的函数调用功能,你能做到这一点,即使你没有从Parent继承。

相关问题