Amir Jalilifard
Amir Jalilifard

Reputation: 2059

How do anonymous functions can solve the default binding error in strict mode?

When we use default binding in strict mode the global object is not eligible for the default binding. Then if we use the below code, we will encounter an error:

    function foo() {
    "use strict";

    console.log( this.a );
}

var a = 2;

foo(); // TypeError: `this` is `undefined`

But when we use an anonymous function as Call-Site,the error disappears.

function foo() {
    console.log( this.a );
}

var a = 2;

(function(){
    "use strict";

    foo(); // 2
})();

So how anonymous function in this code could solve the global object issue and solve the problem?

Upvotes: 2

Views: 100

Answers (1)

Oka
Oka

Reputation: 26355

Adding 'use strict' to the IIFE didn't change the behaviour of foo, removing 'use strict' from foo did.

As the comments above have explained, Strict mode is scoped to the function it is typed in.

These examples will behave the same way as your first example.

function foo() {
  'use strict';
  console.log( this.a );
}

var a = 2;

(function(){
  foo(); // 2
})();

function foo() {
  'use strict';
  console.log( this.a );
}

var a = 2;

(function(){
  'use strict';
  foo(); // 2
})();

And these ones will behave the same way as your second example.

function foo() {
  console.log( this.a );
}

var a = 2;

(function(){
  foo(); // 2
})();

function foo() {
  console.log( this.a );
}

var a = 2;

foo();

Upvotes: 3

Related Questions