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繼承。

相關問題