可以"="功能丢失上下文? [英] Can a "=>" Function Lose Context?
问题描述
我有一个ES6箭头"功能,可用作(淘汰)订阅处理程序:
I have an ES6 "arrow" function which is used as a (Knockout) subscription handler:
this.foo = 'test'
callback = () => console.log(this.foo)
bar.subscribe(callback);
根据MDN:
箭头功能捕获封闭上下文的this值
Arrow functions capture the this value of the enclosing context
所以我希望当callback
被调用时,它会记录'test'
.虽然没有.当我放入调试器时,我可以看到this
实际上是一个ko.subscription
(当然它没有foo
属性).
So I would expect that when the callback
gets called, it would log 'test'
. It doesn't though. When I put a debugger in, I can see that this
is actually a ko.subscription
(which of course doesn't have a foo
property).
我可以通过手动绑定回调来解决问题:
I can fix things by manually binding the callback:
callback = callback.bind(this)
但是据我了解,这不是必需的事情,因为我的this
应该在callback
到达subscribe
之前就已经绑定了.
but as I understood things that shouldn't be necessary because my this
should have been bound before callback
ever got to subscribe
.
有人可以解释一下我对新的=>
运算符不了解的内容,以及何时不保留上下文吗?
Can someone please explain what I'm not understanding about the new =>
operator, and when it does/doesn't preserve context?
推荐答案
首先,感谢大家的帮助.事实证明,这只是Chrome开发人员工具中的一种棘手错误.
First off, thanks everyone for your help. It turns out this is just some sort of screwy Chrome developer tools bug.
这是我的原始代码(未简化):
Here's my original (not simpified) code:
this.snapshot_profile = ko.observable('1');
this.foo = 5;
this.snapshot_profile.subscribe((value) => {
console.log(this.foo);
debugger
// rest of the method
});
事实证明,console.log
将正确返回5
.但是,如果您在调试器行上暂停并将鼠标悬停在this
上,则会看到它不是我的类的实例,而是ko.subscription
.如果我在控制台中检查" this
,它将看起来像这样:
As it turns out, the console.log
will correctly return 5
. However, if you pause on the debugger line and hover over this
, you will see that it is not an instance of my class, but rather a ko.subscription
. If I "inspect" this
in the console, it will look like this:
callback: (value)
dispose: ()
disposeCallback: ()
target: observable()
__proto__: ko.subscription
不像我班上的一个实例.但是(奇怪的是)console.log
行将正确记录5
.
not like an instance of my class. However (strangely) the console.log
line will correctly log 5
.
可以通过直接或通过Knockout的绑定机制绑定功能来修复"以上所有内容.这就是让我感到困惑的地方:在调试器绑定/不绑定中,arrow函数实际上确实改变了一切!
All of the above can be "fixed" by binding the function, either directly or through Knockout's binding mechanism. This is what confused me: in the debugger binding/not binding the arrow function actually did change things!
但是,看起来它并没有真正改变任何有意义的东西.它只是暴露了Chrome调试器中的错误.
But, it looks like it really didn't change anything meaningful; it just exposed a bug in Chrome's debugger.
这篇关于可以"="功能丢失上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!