Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting DedicatedWorkerGlobalScope instead of Constructor

When I print this inside of onScroll handler I get DedicatedWorkerGlobalScope instead of Constructor.

var Frame = React.createClass({
    _handleScroll: (ev) => {
        console.log(this) //DedicatedWorkerGlobalScope
    },
    render: function() {
        return (
            <ScrollView
                ref='scrollViewH'
                onScroll={this._handleScroll}>
                {items}
            </ScrollView>
        );
    }
});

If I handle scroll with inline function this works correct:

var Frame = React.createClass({
    render: function() {
        return (
            <ScrollView
                ref='scrollViewH'
                onScroll={(ev) => {
                    console.log(this) //Constructor
                }}>
                {items}
            </ScrollView>
        );
    }
});

Binding this does not work.

onScroll={this._handleScroll.bind(this)}
like image 692
Sergey Onishchenko Avatar asked Jun 28 '16 07:06

Sergey Onishchenko


2 Answers

When you use the arrow function declaration, you are using 'this' available at the same level as your variable 'Frame', because es6 is inferring the context. This is explained in the article below, which states

[Arrow functions] have implicit return and most importantly, they always use the value of this from the enclosing scope

The article gives a pretty decent explanation how binding syntax works in ES6 and how to get the expected behavior:

https://www.sitepoint.com/bind-javascripts-this-keyword-react/

like image 151
Felipe Avatar answered Oct 31 '22 12:10

Felipe


When I rewrote callback declaration in old fashion way (without ES6 Arrow Functions) it works as expected. Why So?!!!! If some one knows, please give me an answer.

var Frame = React.createClass({
    _handleScroll: function(ev) {
        console.log(this); //Constructor
    },
    render: function() {
        return (
            <ScrollView
                ref='scrollViewH'
                onScroll={this._handleScroll}>
                {items}
            </ScrollView>
        );
    }
});
like image 29
Sergey Onishchenko Avatar answered Oct 31 '22 12:10

Sergey Onishchenko