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
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.