简体   繁体   English

JavaScript Es6 在内部函数中引用 this?

[英]JavaScript Es6 reference this inside inner function?

Es6 classes this always refers to the object in which it was created in, even inside an inner function because it does var _this = this and any reference to this will become _this . Es6 类this始终引用创建它的对象,即使在内部函数中也是如此,因为它确实var _this = this并且对this任何引用都将变为_this However what if I need want to reference the context of an inner function within that class?但是,如果我需要引用该类中内部函数的上下文怎么办?

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
        })
    }
}

How can I refer to the context of Hooks.subscribe inside an es6 class?如何在 es6 类中Hooks.subscribe的上下文?

Assuming you want to reference Hooks's this :假设您要引用 Hooks 的this

And also assuming that the subscribe function returns the original hook object并且还假设subscribe函数返回原始hook对象

You can do:你可以做:

class Body {
    constructor () {
        const hook = Hooks.subscribe('', () => {
            // `this` will still reference `Body`'s objects this
            // `hook` will reference the hook object
        });
    }
}

Because you are using an arrow function this is kept in scope from the parent.因为您使用的是箭头函数, this它保持在父级的范围内。 To reassign this to current scope, remove the arrow function.要将其重新分配给当前范围,请删除箭头功能。

class Body {
    constructor () {
        Hooks.subscribe('', function() {
            // `this` is now the context of Hooks.subscribe
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM