Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

“var” variables, "this" variables and "global" variables - inside a JavaScript Constructor

After my last question, this one is more accurate for me:

example:

function Foo() {
    this.bla = 1;
    var blabla = 10;
    blablabla = 100;
    this.getblabla = function () { 
        return blabla; // exposes blabla outside
    }
}
foo = new Foo();

what I understand now:

this.bla = 1;     // will become an attribute of every instance of FOO.
var blabla = 10;  // will become a local variable of Foo(will **not** become an attribute of every instance of FOO), which could be accessed by any instance of FOO - only if there's a method like "this.getBlabla". that's a "closer" ?
blablabla = 100;  // will define a **new** (or change if exist) global(window) variable.

Do I understand correctly?

Also - if I include var blabla = 10; and the getblabla function that uses it in the contractor, then for every instance of Foo("foo"...), there will be saved a Foo contractor function in the memory that includes this "private" variable. or will it be the same Foo function as place for the private variables - for ALL instances(like "foo") of Foo?

like image 821
Daniel Avatar asked Aug 14 '12 16:08

Daniel


1 Answers

Just to focus on the scope, I'm going to run through this example, (with clearer variables) Afterwards, I'll connect it back to your variables.

var x = "Global scope";
var y = "Not changed.";

function Foo() {
    this.x = "Attribute of foo";
    var x = "In foo's closure";
    y = "Changed!"
    this.getX = function () { 
        return x;
    }
}

// do some logging

console.log(x); // "Global scope"
console.log(y); // "Not changed"
foo = new Foo();
console.log(y); // "Changed!"
console.log(foo.x); // "Attribute of foo"
console.log(x); // "Global scope"
console.log(foo.getX()); // "In foo's closure"

The line: this.x is equivalent to this.bla, and it defines an externally available attribute of a Foo object. y is equivalent to blablabla=100 and then the x within foo is equivalent to your blablabla within foo. Here's a really rough jsfiddle you can run to see this.

like image 56
Jeff Tratner Avatar answered Sep 27 '22 20:09

Jeff Tratner