Var variables, this and global variables are inside the JavaScript constructor

After my last question, this 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 a method like "this.getBlabla". that a "closer" ?
blablabla = 100;  // will define a **new** (or change if exist) global(window) variable.

Do I understand correctly?

Also - if I include the var blabla = 10;function getblablathat uses it in the contractor, then for each instance of Foo ("foo" ...), the function of the Foo contractor will be stored in memory, which includes this variable "private". or will it be the same Foo function as the place for private variables - for ALL instances (like "foo") of Foo?

+5
source share
3 answers

, ( ). .

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

function Foo() {
    this.x = "Attribute of foo";
    var x = "In foo 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 closure"

: this.x this.bla, Foo. y blablabla=100, x foo blablabla foo. jsfiddle, .

+6

, , . (, ​​ blablabla .

. , , , ( this.getblabla ).

:

function initBlaBla() {
    var blabla = 10;
    this.getblabla = function () { 
        return blabla; // exposes blabla outside
    }
}

function Foo() {
    this.bla = 1;
    blablabla = 100;
    initBlaBla.call(this);
}

foo = new Foo();

Foo , . , initBlaBla . , , blabla this.getblabla, 10 . , , .

, :

delete foo.getblabla;
foo.getblabla = "Anything!";
foo = "Anything else.";
+2

Yes, you understand that!
As for the second part of the question, this is all about inheritance, as well as the relationship between the (global) window and the functions defined in it scope (think root). So, everything that you do not specify will look at the ancestor.

This is a terrific good video from Crockford that explains it REALLY well.

+1
source

All Articles