我需要延迟一类对象,事后添加一些函数作为属性。因为这些函数必须引用实例变量才能配置作为属性附加的函数,所以我使用thunk来创建函数并转发第一个函数调用。举一个简化的例子:
function Foo(val) {
this.val = val;
}
// simulates a library call which returns a complex object with methods
// this library call requires access to some of the object information,
// simulated by passing in `type`
function buildWorkFunction(type) {
var f = function() { return this.val; };
if (type === 'string')
f = function() { return this.val.length; };
f.getType = function() { return type; };
return f;
}
function addProperty(Base, prop) {
var thunk = function() {
// typeof is just a simple example of how buildWorkFunction could
// change based on this.val
this[prop] = buildWorkFunction(typeof this.val);
return this[prop].apply(this, arguments);
};
thunk.getType = function() {
return 'TODO'; // <-- this is the part I need help with
};
Base.prototype[prop] = thunk;
}
// simulates instances existing before the module load
var foo = new Foo('foo');
// runs after user requests a module load, runs from the module
setTimeout(function() {
// adding a module specific property to the non-module model
addProperty(Foo, 'getVal');
console.log(foo.getVal());
console.log(foo.getVal.getType());
// simulates instances created after the module load
var bar = new Foo(17);
console.log(bar.getVal.getType()); // called before thunk - fails
console.log(bar.getVal());
console.log(bar.getVal.getType()); // called after thunk - works
}, 0);
&#13;
我遗留的一个问题是,属性的值本身具有应用程序代码有时引用的属性而不调用属性本身,如上面的f.getType
。如何在不先调用foo.getVal.getType()
的情况下正确捕获/代理/转发foo.getVal()
等来电?附加属性的名称已明确定义且可以共享 - 但我无法查看如何访问正确的this
或其中的数据。
答案 0 :(得分:1)
如何正确捕捉/代理
foo.getVal.getType()
等来电?如果先未调用foo.getVal()
,我将无法查看如何从中获取正确的数据或数据。
您可以使用与您相同的方法,但在属性getter级别而不是方法调用级别。这使得可以懒惰地创建任意实例属性:
function addProperty(Base, prop) {
Object.defineProperty(Base.prototype, prop, {
get: function thunk() {
var propertyValue = buildWorkFunction(typeof this.val);
// ^^^^^^^^^^^^^^^ access the instance here
// overwrite (shadow) the prototype getter:
Object.defineProperty(this, prop, {
value: propertyValue,
writable: true,
enumerable: true,
configurable: true
});
return this[prop];
},
enumerable: true, // dunno
configurable: true
});
}