Search code examples
javascriptthisfunction-constructor

How to get context of calling function/object?


function define(prop, value) {
    Object.defineProperty( /* context of caller */ , prop, {value: value});
}

function F() {
    define('x', 42);
}

var f = new F();

Is there a way to get context (inline commented in code above) of the calling function?

It works fine if I bind to this (replace comment to this) and inside F constructor declare var def = define.bind(this);


Solution

  • How to get context of calling function/object?

    You can't, you'll have to make it available to your define function explicitly (pass it in as an argument, etc.).

    And this is a Good Thing(tm). :-) The last thing you'd want is functions having access to the caller's context and changing things in an uncontrolled way.