Вопрос

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

Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top