JS Execution Context

by Ivan Gerasimenko

HTML

<!-- added to LINKS -->

JavaScript

console.clear();
var log = function(msg) { if(msg === undefined) msg = ''; console.log(msg); };
// http://habrahabr.ru/post/149516/

// the main question is IIFY and execution context
// this in func and IIFY is window/global
// this in constructor is created Object

var f = function() {
    this.x = 5;    // this1
    (function() {
        this.x = 3;    // this2
    })();
    console.log('log this3: ' + this.x); // this3
}

var obj = { x: 7, m: function() {
        console.log('obj log: ' + this.x);
    }
}

//log( x ); // x is not defined
log( '--- f(); ' );
log( 'ret: ' + f() ); // log: 3 - ret: undefined
log( x ); // global x is redefined by IIFY!!!

log(); log( '--- new f(); ' );
log( 'ret: ' + new f() ); // log: 5, x is defined in new objext by 5

log(); log( '--- obj.m(); ' );
log( 'ret: ' + obj.m() ); // log: 7, this of m is obj cause m is method of obj

log(); log( '--- new obj.m(); ' );
log( 'ret: ' + new obj.m() );

log(); log( '--- f.call(f); ' );
log( 'ret: ' + f.call(f) ); // log: 5 - ret: undefined

// next function logs 5 cause in f.call(f) context of f is defined by f as 5
log(); log( '--- obj.m.call(f); ' );
log( 'ret: ' + obj.m.call(f) ); // log: 5 - ret: undefined