IIFE context issues

后端 未结 2 1684
温柔的废话
温柔的废话 2020-12-06 06:54

In the following construct:

(function(){

    var x = function(){
        alert(\'hi!\');
    }

    var y = function(){
        alert(\"hi again!\");
    }
         


        
2条回答
  •  难免孤独
    2020-12-06 07:51

    The global context (window in a browser) is the value this gets when there's no other value to use.

    Your local variables are local (that is, not properties of window). They're declared inside the function with var.

    The reason why adding var h = (function(){... makes no difference is because of the way you call the function. The function reference is not a property value of an object (like something.func()), and you don't invoke it with .call() or .apply(), so therefore this refers to the global (window) object. That's just the way the language is defined to act.

提交回复
热议问题