Search code examples
javascriptoopfunction-prototypesprocedural-programming

Why does object prototype methods have no caller in oop unlike in procedural programming


If I have a procedural function calling another procedural function like this:

function awesome() {
    return arguments.callee.caller.name;
}
function ridiculous() {
    return awesome();
}
ridiculous();

Then I get back the caller named "ridiculous". But when I write it in oop-style, then the caller is null.

function myObj() {}
myObj.prototype.awesome = function() {
    return arguments.callee.caller.name;
}
myObj.prototype.ridiculous = function() {
    return this.awesome();
}

I wonder, why this happens and how to get back the caller anyway.


Solution

  • The key in the object and the name of the function isn't the same thing.

    Take a look at my snippet:

    function myObj() {}
    myObj.prototype.awesome = function awesome() {
        return arguments.callee.caller.name;
    }
    myObj.prototype.ridiculous = function ridiculous() {
        return this.awesome();
    }
    
    var o = new myObj();
    console.log(o.ridiculous())