Does javascript function have scope?

If functions have a scope, they should be executed within that scope, but here I think they are different. See the code:

function foo() {
    var privateVal = "Private Val";
    this.publicVal = "Public Val";

    var privateAlert = function (str) {
        alert(str + this.publicVal);
        alert(str + privateVal);
    }

    this.Run = function () //see here
    {
        privateAlert("Private Call: ");

        this.publicAlert = privateAlert;
        this.publicAlert("Public Call: ");

        privateAlert = this.publicAlert;
        privateAlert("Private Call: ");
        this.publicAlert("Public Call: ");
    }
}

var bar = new foo();
bar.Run();

      

When a new object is created, Run()

it becomes a public method of the object, or the tht method is owned only by var bar

. This method does not have to perform a function privateAlert()

internally; since the function has scope, it can only be executed from the function it has declared, but the function has lost the scope in which it was created and it is still executing. Please clarify this?

+3


source to share


1 answer


Simple explanation:

  • Any variable declared inside a function is not accessible outside of that function.
  • Inner functions have access to variables declared in their outer scopes (see closures ).


So, you can call privateAlert

from Run

because both are defined internally foo

.

One more thing: Run

not a private method bar

, it is a public method.

+6


source







All Articles