dynamic命名一个方法
是否可以dynamic地命名一个方法?
让我们说:
Class.prototype[name] = function(param) { console.log(name, param) }
所以如果我这样做:
// will return `hello there` class.hello('there') // will return `hey there` class.hey('there')
这可能吗?
我正在使用库zerorpc 。
他们有一个语法
client.invoke("iter", 10, 20, 2, function(error, res, more) {
所以我想创build一个类来包装他们的function,所以我可以做这样的事情:
client.iter(10,20,2 function(...
这是我的尝试:
var zerorpc = require('zerorpc') var util = require('util') var EventEmitter = require('events').EventEmitter var RPC = function () { if (!(this instanceof RPC)) return new RPC() this.rpc = new zerorpc.Client() } util.inherits(RPC, EventEmitter) module.exports = RPC() RPC.prototype.connect = function(config) { this.con = this.rpc.connect('tcp://' + config.host + ':' + config.port) } // this is the idea RPC.prototype[name] = function(params) { this.rpc.invoke(name, params[0], params[1], params[2], function(error, res, more) { // ... }
在gitbub的要点看这个。
你在找代理吗?
var obj = Proxy.create({ get: function(target, value) { return function() { console.log('called ' + value) } } }); obj.hello(); // "called hello" obj.world(); // "called world"
您必须使用--harmony_proxies
选项来启用节点中的代理。