HTML and CSS Reference
In-Depth Information
the preceding code, you can begin to create instance variables that exist only
within the scope of each World object , such as its name.
var World = function(_name){
var name = _name;
this.greet = function(guest){
alert('Hello ' + guest + ' my name is ' + name);
var venus = new World('Venus');
var mars = new World('Mars');
From the preceding examples, you can see that in order to create an object in
JavaScript, it's as simple as creating a function. Using the function's
parameters, you create what is called a constructor. A constructor is a method
to pass parameters to the object upon instantiation. These parameters are
usually used to assign variables to properties within the object itself.
A property can be declared as public or private in normal object orientation. In
JavaScript there are no such declerations available for properties. So a property
can either be an instance variable (private) or a public property (public). In this
instance, the name property is an instance variable, which means that you cannot
access it from outside of the object using, for example, . This is
generally known as encapsulation. A property of an object is a variable that can
be accessed either by using this.propertyname from within the object's scope,
or by using object.propertyname from outside of the object. For example, if you
attempted to access the name instance variable from outside of the object, you
would get undefined as the output.
You can also create object methods, which are functions that can be accessed
from within or outside of the object using this from within the object or the
variable assigned to the instantiated object from outside. Using the previous
examples, this.greet is a public object method and can be accessed outside of
the object.
From here, you can see that objects allow for much more maintainable code.
The object's properties live outside of the global namespace, so you avoid
clashing variable names and other details for specific objects. You can go
beyond this and create your own namespace for your application objects. This
helps to avoid other JavaScript libraries from potentially overwriting them. The
Search WWH ::

Custom Search