JavaScript objects are at the heart of every application. Unfortunately theres alot of misuse of objects. Before diving into this brief explination I want to start by saying “If you understand the framework, the rest is just syntax”. Dont get caught up on trying to understand all of the syntax.
Think of an object as a container. That containers content should be relevant to its purpose. A container with a collection of properties and methods.
Lets use the car example. To begin were going to create a model that will represent what a car is. Then we will actually create a car when finished. The car being the JavaScript object:
var car= (function(){ /* I'm inside of the car. */ });
A car has several properties like fuel level, tire pressure. It may even have safety features like traction control or airbags.
var car = (function(){
var root= this;
root.properties = {
fuelLevel: "100%",
tirePressure: "high",
headLights: 'on',
engine:"off"
};
});
The car now contains the properties we can later use. Cars aren’t just for show though. They move, accelerate, brake. Maybe even have a few other features like heat or sunroof.
var car = (function(){
var root= this;
root.properties = {
fuelLevel: "100%",
tirePressure: "high",
headLights: 'on',
engine:"off"
};
root.actions = {
start:function () { root.properties.engine = "on"; alert("car started"); },
drive:function () { alert("driving away"); },
turn:function () { },
signal:function () { }
};
});
Now that we have finished our closure, lets use the car!
var myCar= new car();
My myCar object is now using the car model we designed. Let’s start it up.
if( myCar.properties.fuelLevel > 0 ) {
myCar.actions.Start();
}
Now lets drive our car. But wait. You can’t drive a car that’s not started so let’s check to see if it’s started first.
if( myCar.properties.engine == "on" ) {
myCar.actions.drive();
}
Summary:
By enclosing related javascript properties and methods, your enabling better reuse of your code. This will in the end improve performance.
-
together12up liked this
-
mickeyelliott posted this