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 mented in code above) of the calling function?
It works fine if I bind to this (replace ment to this
) and inside F
constructor declare var def = define.bind(this);
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 mented in code above) of the calling function?
It works fine if I bind to this (replace ment to this
) and inside F
constructor declare var def = define.bind(this);
-
1
stackoverflow./questions/9679053/…, looks like you have to pass
this
to define – Patrick Evans Commented Jun 30, 2013 at 17:38 -
Yeah, question is there a way to do it without passing
this
– jsguff Commented Jun 30, 2013 at 17:44 -
define.call(this, 'x', 42);
? ThenObject.defineProperty(this, ...)
– user2437417 Commented Jun 30, 2013 at 17:45 -
...or just put your
define
function onF.prototype
likeF.prototype.define = define
, so you can dothis.define(...)
in the constructor, andthis
indefine
will automatically be your object. – user2437417 Commented Jun 30, 2013 at 17:50 -
@CrazyTrain, putting define in
F.prototype
andthis.define(...)
looks better than binding, but that isn't mon case. – jsguff Commented Jun 30, 2013 at 18:09
1 Answer
Reset to default 5How 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.