Calling function with window scope explanation (0, function(){})()

前端 未结 2 727
囚心锁ツ
囚心锁ツ 2020-12-03 00:00

I am curious as to why this works:

var c = {
    d: function myFunc() {
        console.log(this === window);   
    }
};
var a = {
    b: function() {
              


        
2条回答
  •  借酒劲吻你
    2020-12-03 00:32

    If you write multiple expressions separated by a comma (,), then all expressions will be evaluated, but you will end up with the value of the last expression:

    var x = (1,2,3);
    console.log(x); // this will log "3"
    

    Now (0,c.d) is an expression that will return the function c.d, but now c is not the this of the function anymore. This means that this will point to the global object (window), or remain undefined in strict mode. You would get the same effect with any of these:

    var f = function(x) { return x; };
    f(c.d)();
    

    Or just

    var f = c.d;
    f();
    

提交回复
热议问题