Question

Consider this piece of code:

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();

Is it possible to determine if Parent.myMethod() is being called "naturally" or through "override" and in that case return something else?

DEMO

Was it helpful?

Solution

Is it possible to determine if Parent.myMethod() is being called "naturally" or through "override"

Not really (without resorting to the non-standard, deprecated caller property). But you can detect when the method is called on an object that has a different myMethod property:

this.myMethod === Parent.prototype.myMethod

and in that case return something else?

You really should not. Make it a parameter (but beware) that you expect something else, or divide the functionality in two different methods.

OTHER TIPS

As I see it, you don't override the method, by passing this into the call function you call the function like it is Child's function, you could do that even if you didn't inherit from Parent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top