Scoping of variables in Javascript

satya - 4/21/2014 10:44:34 AM

Little bit of research on this and that in javascript

Little bit of research on this and that in javascript

satya - 4/21/2014 10:44:48 AM

Scoping of variables in Javascript

Scoping of variables in Javascript

Search for: Scoping of variables in Javascript

satya - 4/21/2014 11:01:35 AM

an article I ran into

an article I ran into

satya - 4/21/2014 11:08:33 AM

Variable outside of any function is a global variable


var xyz = "Global";
xyz = "Global as well";
function f()
{
    var xyz = "local, overrides the global one";
    var abc = "local. Not seen outside of the function";
    abc = "Global again, but available only after f() is called once";
    for (....)
    {
       var blah = "No such thing as block level scope but only function level";
    }
}

satya - 4/21/2014 11:09:17 AM

Not having a var against a variable ...

Makes the variable scope walk up the chain and declare it globally....

satya - 4/21/2014 11:12:55 AM

Hoisting: Definitions are automatically moved to the top of the scope


//call f()
f();
//define f() later
function f() {}

//becomes
//define f() later
function f() {}

and

f();

satya - 4/21/2014 11:14:58 AM

another


alert(helloVariable);
var helloVariable = "xyz";

//becomes

var helloVariable;
alert(helloVariable);
helloVariable = "xyz";

satya - 4/21/2014 11:16:31 AM

ECMA script introduced block level scoping through let and const

ECMA script introduced block level scoping through let and const

Search for: ECMA script introduced block level scoping through let and const

satya - 4/21/2014 11:31:47 AM

Public and private variables


function f()
{
  var abc; //private
  this.xyz; //public member available outside through new
}

satya - 4/21/2014 11:36:11 AM

Private members are not accessible to public methods unlike oo languages!!!


function f()
{
  var abc; //private
  this.xyz; //public member available outside through new
  var function privatef() 
  {
     //private function
     //can use abc and xyz
  }
  this.publicfunc = function publicf() 
  {
     //public function
     //cannot see private varilabe abc????
  }
}

satya - 4/21/2014 11:39:02 AM

This can be overcome by creating a public variable pointing to this


function f()
{
  var abc; //private
  this.xyz; //public
  this.that = this; //trozan horse

  this.publicfunc = function publicf() 
  {
     //public function
     //cannot see private varilabe abc????
     //Now it can
     console(that.abc);
  }
  
}

satya - 4/21/2014 11:42:21 AM

Crockford on private functions

Crockford on private functions

satya - 4/21/2014 11:46:47 AM

So in Javascript objects remember that there are..


Private variables
Private functions
Public variables
Public functions
Public functions that get privileged through the "that" variable