gpt4 book ai didi

javascript - 动态命名方法

转载 作者:行者123 更新时间:2023-11-30 05:34:58 25 4
gpt4 key购买 nike

是否可以动态命名一个方法?

让我们说:

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) {

所以我想创建一个类来包装它们的功能,这样我就可以做类似的事情:

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 上看到这个 gist .

最佳答案

你在找proxies吗?

var obj = Proxy.create({
get: function(target, value) {
return function() {
console.log('called ' + value)
}
}
});

obj.hello(); // "called hello"
obj.world(); // "called world"

您必须使用 --harmony_proxies 选项在 Node 中启用代理。

关于javascript - 动态命名方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24427630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com