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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
jsguff
  • 105
  • 1
  • 5
  • 1
    http://stackoverflow.com/questions/9679053/is-it-possible-to-get-the-caller-context-in-javascript, looks like you have to pass `this` to define – Patrick Evans Jun 30 '13 at 17:38
  • Yeah, question is there a way to do it without passing `this` – jsguff Jun 30 '13 at 17:44
  • `define.call(this, 'x', 42);`? Then `Object.defineProperty(this, ...)` –  Jun 30 '13 at 17:45
  • ...or just put your `define` function on `F.prototype` like `F.prototype.define = define`, so you can do `this.define(...)` in the constructor, and `this` in `define` will automatically be your object. –  Jun 30 '13 at 17:50
  • @CrazyTrain, putting define in `F.prototype` and `this.define(...)` looks better than binding, but that isn't common case. – jsguff Jun 30 '13 at 18:09

1 Answers1

4

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875