Javascript Encapsulation

I am new to Javascript since my SO profile will attest.

I just read a few tutorials and came across something that I don’t quite understand regarding Object Orientation and Encapsulation when applied with Javascript.

The tutorial states that Javascript objects can be declared as follows:

var myCustomObject = new Object();

And you can give it instance variables like this:

myCustomObject.myVariable = "some value";
myCustomObject.myOtherVariable = "deadbeef";

Finally, it says that you can create a template function to create new objects, such as:

function CustomObject(myVariable, myOtherVariable)
{
    this.myVariable = myVariable;
    this.myOtherVariable = myOtherVariable;
}

I also know that you can create and assign values ​​to variables that do not yet exist, and as a result are declared implicitly, as shown in the example where it myCustomObjectdoes not myVariable, but now it does.

, : , - . , , / , , - .js , , , ...

, , - , , , 60 , , ?

, , , "willy nilly"?

+5
4

Javascript (TM), .

, . , , "", , "". :

var Vehicle = function(){}

var factory = {
    create: function(name, props){
        var v = new Vehicle();
        v.type = name;
        for(var prop in props) {
            v[prop] = props[prop];
        }
    }
}

var bike = factory.create('Bike', {
    wheels: 2
});

var car = factory.create('Car', {
    wheels: 4,
    doors: 5,
    gear: 'automatic'
});

var plane = factory.create('Airplane', {
    wings: 2,
    engines: 4
});

, , , , :

// lets paint our car
car.color = 'candy red';
// bling!
car.racingStripes = true;
car.mirrorDice = true;
car.furryChairs = true;

/ .

+1

, , ...

JavaScript . , , , . JavaScript, , , .

+7

: .

:

Javascript - -, . , , , , . (, , ), .

, , . , : http://javascript.crockford.com/private.html.

, , , .

:

javascript , , / . java, , , ape java.

+2

, , ;) .

, - , :

function myConstructor()
{
  var myState = {}; //Create new, empty object
  myState.text = "Hello World!";
  this.say = function() {
    alert(myState.text);
  };
}

In this simple example, you can store internal variables in myState (or "var text = '';" etc.), and they are not accessible from the outside, since they are not members of the object, they are only private variables in your function. And, as you can see, the function says that it still has access to it.

+2
source

All Articles