从三元运算符返回的函数中丢失上下文 [英] Losing context from function returned by ternary operator
问题描述
我知道如何解决这个特定的问题,但是我想知道为什么会发生.基本上,当我尝试调用这样的函数时:
I know how to get around this particular problem, but I would like to know why it happens. Basically, when I try to invoke a function like this:
(callFoo ? this.foo : this.bar)();
它调用正确的foo函数,但是在foo内部, this
是全局的窗口对象,而不是我期望的对象.
It calls the correct foo function, but inside of foo, this
is the global, window object instead of the object I expect.
我希望这可以做同样的事情,但事实并非如此:
I would expect that this does the same thing but it does not:
(this.foo)();
上面的代码调用正确的函数并维护正确的上下文( this
是我期望的).
The code above calls the right function and maintains the correct context (this
is what I expect it to be).
有人可以解释发生了什么吗?我知道如何解决这个问题(我什至都不喜欢这种语法),但是我仍然想知道如果您从三元运算符返回一个函数,为什么 this
成为窗口.
Could someone please explain what is going on? I understand how to get around the problem (I'm not even a fan of that syntax), but I still want to know why this
becomes the window if you return a function from a ternary operator.
编辑
我想完善我的问题:对我来说,这很有意义:
EDIT
I'd like to refine my question:
It makes sense to me that this:
(callFoo ? this.foo : this.bar)();
等效于:
var f = (callFoo ? this.foo : this.bar);
f();
这对我来说很有意义,为什么 this
成为该函数中的窗口.
And it makes sense to me why this
becomes the window within that function.
为什么这里不发生相同的事情:
Why doesn't the same thing happen here:
(this.foo)();
推荐答案
造成差异的原因:
var obj = new (function MyConstructor(){
this.getConstructor = function(){ return this.constructor.name; }
});
任何操作员对操作数进行操作时,结果的工作方式都非常类似于函数的返回值.传递的对象方法不再像绑定到对象一样对待.
When operands are operated on by any operator, the results work much like the return value of a function. An object method passed is no longer treated like it's tied to the object.
(function(){ return obj.getConstructor; })(); //'Window'
但是,在除属性访问以外的其他任何内容都没有发生的情况下,paren只会被忽略,而不是被当作运算符本身.所以:
But in the case where nothing is happening inside the parens other than property access, the parens are simply ignored rather than treated as operators themselves. So:
(obj.getConstructor)(); //'MyConstructor'
真的等同于:
obj.getConstructor();
但是添加导致该方法的任何有效操作
But add a valid operation of any kind resulting in the method:
(false || obj.getConstructor)(); //'Window'
并且obj.getConstructor被视为已传递的方法,而不是通过'.'绑定到对象的方法.关联.
And obj.getConstructor is treated as a method that's been passed rather than a method tied to an object via the '.' association.
这篇关于从三元运算符返回的函数中丢失上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!