我可以使用 y-combinator 来获取此闭包的对象引用吗?
这个闭包有效:
var o = {
foo: 5
};
o.handler = function(obj){
return function() {
alert(obj.foo);
};
}(o);
o.handler(); //alert('5')
是否可以内联定义处理程序,也许使用类似于 y 组合器操作的东西?
var o = {
foo: 5,
handler: function(obj){
return function() {
alert(obj.foo);
};
}(o); //pointer to o? -----------------------------
};
出于学术好奇心,我不想在生产代码中执行此操作
this closure works:
var o = {
foo: 5
};
o.handler = function(obj){
return function() {
alert(obj.foo);
};
}(o);
o.handler(); //alert('5')
is it possible to define handler in-line, perhaps with something similar to a y-combinator operation?
var o = {
foo: 5,
handler: function(obj){
return function() {
alert(obj.foo);
};
}(o); //pointer to o? -----------------------------
};
out of academic curiosity, I'm not trying to do this in production code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这是不可能的,因为在定义对象字面量时,变量
o
是未定义的,而定义时的this
引用也没有定义。参考o
。如果您在外部函数中使用对
this
的临时引用并将其传递到闭包中,它会起作用,但您将无法传入对象来获取foo属性出来了。
No, this is not possible, because at the time of definition of the object literal, the variable
o
is undefined, and thethis
reference at the time of definition doesn't referenceo
.If you used a temporary reference to
this
in the outer function and passed it into the closure, it would work, but you would not be able to pass in an object to get thefoo
property out of.正如其他人指出的那样,这对于对象文字本身来说是不可能的。然而,该过程可以被包装。它是否“增加了任何东西”是值得商榷的。这与 Y-Combinator 不同(也许是它的一半?),因为它并没有试图给出一个“递归名称”(据我所知,Y-Combinator 假设一流的函数和闭包或模拟这样的方法)。
未经测试,但展示了一种可以采用的方法。这和
dict
/res
上的原型链(如果有的话)存在一些微妙的问题——供读者练习。快乐编码。
This is not possible with an object literal by itself, as others have pointed out. However, the process can be wrapped. Wether or not it "adds anything" is debatable. This isn't the same as a Y-Combinator (perhaps half of it?), because it is not trying to give a "recursive name" (as far as I can tell Y-Combinators assume first-class functions and closures or a way to simulate such).
Not-tested, but shows an approach that could be taken. There are subtle issues with this and a prototype chain on
dict
/res
, if any -- an exercise for the reader.Happy coding.
您可以在此处使用
this
关键字:这是一种更简单的方法...实际上,您的方法甚至是不可能的,因为当您引用时未定义
o
它。You could just use the
this
keyword here:That's a lot easier approach... Actually, your approach isn't even possible, as
o
is not defined when you refer to it.