Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 528
jsguff Avatar asked Oct 04 '22 16:10

jsguff


1 Answers

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.

like image 98
T.J. Crowder Avatar answered Oct 07 '22 17:10

T.J. Crowder