HTML and CSS Reference
In-Depth Information
The second method, which is object oriented, is shown next.
var World = function(){
this.say = function say(hello){
alert(hello);
}
}
var myworld = new World();
myworld.say('Hello');
As you can see, you might need to write more code for the object-oriented
approach, but there are several benefits.
The object-oriented approach allows for expansion of your
code.
The object-oriented approach can be much more organized.
The object-oriented approach allows for encapsulation, which
means that variables or properties within your objects can be
public or private.
The object-oriented approach allows you to pass objects into
other objects. This is known more commonly as object
dependencies.
NOTE: In class based languages such as Java, Objective-C and PHP
a class is an object before it is instantiated by using new ClassName.
An object is an instance of a class after it has been instantiated.
JavaScript has basic methods for creating objects and, unfortunately,
doesn't fully support encapsulation, inheritance, abstraction, and
interfaces out of the box. You might need to create your own methods
and practices for implementing this. JavaScript is also an object based
language, so although it feels like you're creating classes, you're
actually creating structures in code for your objects to take form from.
Both of the preceding code snippets have the same result; however, the object-
oriented approach treats World as an object, and the function within that object,
this.say , as a method that can be performed on it.
The object-oriented approach also allows you to create multiple instances of an
object. For example, you can create several World instances, and by modifying
Search WWH ::




Custom Search