Search code examples
javascriptvar

The var keyword scope and function name used to access variables


How is prop1 still accessible outside function body?

function myFunc() {
  var prop1 = 10;
  this.myChildFunc = function() {
    alert("value of prop1: " + prop1);
  }
}

myFunc();
myFunc.prop1 = 20; // How prop1 is still accessible using function name ? and outside function scope?
alert("prop1:" + myFunc.prop1);


Solution

  • Functions are objects, so they can have properties, but these are just properties, nothing more than that.

    So, the variable you've declared inside the function (var prop1) has nothing to do with the property on the function object (myFunc.prop1). They just have the same name.

    To see it, let's look at this:

    function myFunc() {
      var prop1 = 10;
      console.log(prop1);
    }
    
    myFunc();                  //10
    console.log(myFunc.prop1); //undefined - no such property
    myFunc.prop1=20;           //myFunc.prop1 is now 20
    myFunc();                  //variable is still 10
    console.log(myFunc.prop1); //property is still 20