有没有一种方法可以在javascript中指定类似下面的内容?
var c = {};
c.a = function() { }
c.__call__ = function (function_name, args) {
c[function_name] = function () { }; //it doesn't have to capture c... we can also have the obj passed in
return c[function_name](args);
}
c.a(); //calls c.a() directly
c.b(); //goes into c.__call__ because c.b() doesn't exist发布于 2010-10-05 04:02:28
不,不是真的。有一些替代方案-尽管不像您的示例那样好或方便。
例如:
function MethodManager(object) {
var methods = {};
this.defineMethod = function (methodName, func) {
methods[methodName] = func;
};
this.call = function (methodName, args, thisp) {
var method = methods[methodName] = methods[methodName] || function () {};
return methods[methodName].apply(thisp || object, args);
};
}
var obj = new MethodManager({});
obj.defineMethod('hello', function (name) { console.log("hello " + name); });
obj.call('hello', ['world']);
// "hello world"
obj.call('dne');发布于 2010-10-05 03:35:41
Mozilla实现了,但实现了otherwise...no。
发布于 2016-05-18 17:59:15
差不多6年后,终于有了一种方法,使用Proxy
const c = new Proxy({}, {
get (target, key) {
if (key in target) return target[key];
return function () {
console.log(`invoked ${key}() from proxy`);
};
}
});
c.a = function () {
console.log('invoked a()');
};
c.a();
c.b();
https://stackoverflow.com/questions/3858415
复制相似问题