Javascript重载括号

时间:2015-04-04 05:41:42

标签: javascript

我希望能够在javascript中合并对象和函数。目前我有这样的代码:

var Functor = function(f, prop) {
  var inst = function() {return inst.__op__.apply(this, arguments)}
  inst.__op__ = f
  for (var key in prop)
    inst[key] = prop[key]
  return inst
}

用法是这样的:

var x = Functor(function(arg) {console.log(arg)}, {qwe:123})
console.log(x.qwe) // 123
x(321) // 321

但我有两个问题:首先,我不喜欢将prop参数的属性复制到返回的inst,我希望有一些指向prop的链接。其次,我希望能够在第一个this参数中添加Functor以获取inst的链接。似乎我的问题可以解决重塑Functor函数以使用new关键字。但我无法弄清楚如何做到这一点。

重要的功能是我能够更改__op__属性(这是()运算符)并且我可以绑定结果并获得正确的行为:

var x = Functor()
x.__op__ = console.log
var echo = x.bind(console)
echo(123) // 123

如果有人能解决我的任何问题,我将不胜感激 这里有一个代码复制的小提琴:http://jsfiddle.net/avmhbyzr/

1 个答案:

答案 0 :(得分:1)

为避免复制prop的所有属性,您可以将prop设置为inst的原型。由于inst是一个函数(不是普通对象),因此您无法控制其构造函数(它必须是Function),因此更改其原型的唯一方法是通过内部{{1属性。

直接的缺点是,您无法访问函数的所有方法,例如你不能调用x.call()。但是你可以通过将Function.prototype链接到prop来解决它。请参阅下面的代码。

__proto__

至于var Functor = function(f, prop) { var inst = function() { return inst.__op__.apply(this, arguments) } // Setup prototype chain: inst -> prop -> Function.prototype prop.__proto__ = inst.__proto__ inst.__proto__ = prop inst.__op__ = f return inst } !function() { var x = Functor(null, {qwe:123}) console.log(x.qwe) // 123 // Method 1: bind the context to __op__ x.__op__ = console.log.bind(console) x(321) // 321 // Method 2: call x with the context x.__op__ = console.log x.call(console, 321) // 321 }() 的使用,您已经通过this正确地将上下文传递到__op__ {/ 1}}。

传递上下文的方法是通过使用上下文调用inst(方法2),或者使用更笨拙的Function.prototype.apply。如果您不想这样做,您始终可以将上下文绑定到x(方法1)。

请记住,执行函数时,它需要上下文(console.x = x; console.x(321))和参数。上下文要么永久地绑定到函数(方法1),要么就地提供(方法2)。

相关问题