Wednesday, May 27, 2015

So you know JavaScript?!

So you know JavaScript language and quite confident that you can write some program with that funny language. Are you sure? Really? Can you answer below simple question?

1.

var action = "sleep";

var spiderman = {
  action : "climb",
  showPower : function () {
    "use strict";
    console.log(this.action)
  }
}

var somePower = spiderman.showPower;
somePower();

Answer 

1. "sleep"
2. "climb"
3. Error

Correct answer is 3. If you guess 1 or 2 you have proven yourself you don't know much about the language. 

Why 3? 
'this' is set from the execution context when the function runs. In this case 'this' is not set at the time of the function execution as it runs on global context.

ECMAScript5  'use strict' makes sure 'this' is not set to global context. (It was a bug in early ECMAScript specifications)

Answer 1 is wrong because function runs on strict mode as explains above. Remove "use strict" statement and you will get answer 1.

Answer 2 is wrong because the function is not executing on spiderman object. Below change gives answer 2.

spiderman.showPower() // output:  climb

Now the execution context is 'spiderman' and 'this' is set to 'spiderman' at the time of the function execution.  

This is a crazy language isn't it!