JavaScriptES6引用了这个内部函数吗?
Es6类JavaScriptES6引用了这个内部函数吗?,javascript,ecmascript-6,Javascript,Ecmascript 6,Es6类this始终引用在其中创建它的对象,即使在内部函数中也是如此,因为它确实var\u this=this,对this的任何引用都将变成\u this。但是,如果我需要引用该类内部函数的上下文,该怎么办 class Body { constructor () { Hooks.subscribe('', () => { // I want this to reference the context that is within this m
this
始终引用在其中创建它的对象,即使在内部函数中也是如此,因为它确实var\u this=this
,对this
的任何引用都将变成\u this
。但是,如果我需要引用该类内部函数的上下文,该怎么办
class Body {
constructor () {
Hooks.subscribe('', () => {
// I want this to reference the context that is within this method
// elsewhere because bind,apply,call sets new context
})
}
}
如何在es6类中引用Hooks.subscribe
的上下文?因为您使用的是箭头函数此保留在父类的范围内。要将其重新分配给当前作用域,请删除箭头函数
class Body {
constructor () {
Hooks.subscribe('', function() {
// `this` is now the context of Hooks.subscribe
});
}
}
假设您想引用钩子的此:
并且还假设subscribe
函数返回原始hook
对象
你可以做:
class Body {
constructor () {
const hook = Hooks.subscribe('', () => {
// `this` will still reference `Body`'s objects this
// `hook` will reference the hook object
});
}
}
因此,您希望this
成为Hooks
?this
的行为在类内不会改变,但在lambdasFat arrow函数(lambdas)中会改变,它将作用域绑定到周围的作用域,因此如果您只使用function(){}
。请明确说明您希望函数中此
的值。您在问题中表达了至少三种不同的愿望:“内部函数的上下文”、“此方法中的上下文”和“Hooks.subscribe的上下文”。顺便说一句:这个
从来没有提到过上下文。当然,这指的是@zeroplagl的上下文。你认为它还意味着什么?除非我一直在用上下文这个词,否则你说的“钩子的这个”和“身体的物体的这个”是什么意思<代码>此
不能归因于对象。