Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

loops, closures and incorrect "this" value #65

Open
yernende opened this issue Nov 4, 2014 · 0 comments
Open

loops, closures and incorrect "this" value #65

yernende opened this issue Nov 4, 2014 · 0 comments

Comments

@yernende
Copy link

yernende commented Nov 4, 2014

If using declared in header of for-of loop variable in closure, placed in this loop, keyword "this" in that closure becomes equal to global object.

var servant = {
    sayNumbers() {
        for (let number of [1, 2, 3]) {
            (() => {
                number; //without number reference "this" is right
                console.log(this); //window
            })();
        }
    }
}
servant.sayNumbers();

This code is compiled into

var servant = {
    sayNumbers: function() {var S_ITER$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol.iterator||'@@iterator';var S_MARK$0 = typeof Symbol!=='undefined'&&Symbol&&Symbol["__setObjectSetter__"];function GET_ITER$0(v){if(v){if(Array.isArray(v))return 0;var f;if(S_MARK$0)S_MARK$0(v);if(typeof v==='object'&&typeof (f=v[S_ITER$0])==='function'){if(S_MARK$0)S_MARK$0(void 0);return f.call(v);}if(S_MARK$0)S_MARK$0(void 0);if((v+'')==='[object Generator]')return v;}throw new Error(v+' is not iterable')};var $D$0;var $D$1;var $D$2;var $D$3;
        $D$3 = ([1, 2, 3]);$D$0 = GET_ITER$0($D$3);$D$2 = $D$0 === 0;$D$1 = ($D$2 ? $D$3.length : void 0);for (var number ;$D$2 ? ($D$0 < $D$1) : !($D$1 = $D$0["next"]())["done"];){number = ($D$2 ? $D$3[$D$0++] : $D$1["value"]);(function(number){var this$0 = this;
            (function()  {
                number;
                console.log(this$0); //window
            })();
        })(number);};$D$0 = $D$1 = $D$2 = $D$3 = void 0;
    }
}
servant.sayNumbers();

And all works fine if function, closing "number" variable, is called via "call" method with definition of "this".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant