最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get context of calling functionobject? - Stack Overflow

programmeradmin1浏览0评论
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);

Share Improve this question edited Jun 16, 2015 at 8:40 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 30, 2013 at 17:35 jsguffjsguff 1051 silver badge5 bronze badges 5
  • 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);? Then Object.defineProperty(this, ...) – user2437417 Commented Jun 30, 2013 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. – user2437417 Commented Jun 30, 2013 at 17:50
  • @CrazyTrain, putting define in F.prototype and this.define(...) looks better than binding, but that isn't mon case. – jsguff Commented Jun 30, 2013 at 18:09
Add a ment  | 

1 Answer 1

Reset to default 5

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.

发布评论

评论列表(0)

  1. 暂无评论