Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do function in javascript have scope?

If functions have the scope, they should be executed within that scope, but here I think it's 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 the new object is created, Run() becomes the public method of an object or the method tht only belongs to the var bar. That method shouldn't be able to execute the privateAlert() function from within it; since function has the scope, it can only get executed from within the function it has been declared but this function have lost the scope where it was created and it is still getting executed . Clarify this please?

like image 803
Maizere Pathak Avatar asked Nov 22 '25 19:11

Maizere Pathak


1 Answers

The simple explanation:

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

So, you can call privateAlert from Run because both have been defined inside of foo.

One more thing: Run is not a private method of bar, it's a public method.

like image 153
bfavaretto Avatar answered Nov 24 '25 07:11

bfavaretto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!