Binding context when calling ES6 method. How to access object from within method called as callback?

后端 未结 3 464
无人及你
无人及你 2020-12-01 16:50

I\'m trying to wrap my head around the syntax for Classes in ES6. While at the same time learning Fabric native through Bonnie Eisenman\'s Learning React Native.

I\'

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 17:28

    Perhaps I've misunderstood a fundamental aspect of JavaScript (I'm a beginner in JS), but this seems completely insane to me. Is there really no way of accessing the context of an object from within a method without explicitly binding the object back onto... it's own method, at the point where it is called?

    Well, "methods" are not owned by objects in javascript. All functions are first-class values (objects), and not "part" of an object or a class.

    The binding of the this value happens when the function is called, depending on how the function is called. A function call with method notation has its this set to the receiving object, an event listener call has its this set to the current event target, and a normal function call only has undefined.

    If you are accessing a method on an instance, it's really just the standard prototype inheritance property access which yields a function, which is then called and dynamically-bound to the receiver.

    If you want to call a function as a method on an instance when it is an event listener, then you need to explicitly create a function that does this - the "bound" method. In ES6, the arrow notation is usually preferred for this.

提交回复
热议问题