【发布时间】:2013-06-30 17:35:57
【问题描述】:
function define(prop, value) {
Object.defineProperty( /* context of caller */ , prop, {value: value});
}
function F() {
define('x', 42);
}
var f = new F();
有没有办法获取调用函数的上下文(上面代码中的内联注释)?
如果我绑定到这个(将注释替换为this)并在F构造函数中声明var def = define.bind(this);,它工作正常
【问题讨论】:
-
stackoverflow.com/questions/9679053/…,看来你必须通过
this来定义 -
是的,请问有没有办法不通过
this -
define.call(this, 'x', 42);?然后Object.defineProperty(this, ...) -
...或者只是把你的
define函数放在F.prototype上,比如F.prototype.define = define,这样你就可以在构造函数中做this.define(...),而define中的this会自动你的对象。 -
@CrazyTrain,将define 放入
F.prototype和this.define(...)看起来比绑定好,但这并不常见。
标签: javascript this function-constructor