We can achieve Object Oriented Programming in JavaScript with a little effort.
Creating an Object in JavaScript
There are two ways to create a JavaScript object. They are Constructor functions
and Literal notation
.
function myObject(){ };Literal Notation
var myObject = { };
Literal notation is a preferred option so that the JavaScript code doesn't interfere with other scripts running on the page and also if you are using this object as a single object and not requiring more than one instance of the object; whereas Constructor function type notation is preferred if you need to do some initial work before the object is created or require multiple instances of the object where each instance can be changed during the lifetime of the script.
Defining Methods and Properties in JavaScript ObjectLet us create an object with a property named myProperty and a method named myMethod.
Constructor Functionsfunction myObject(){ this.myProperty = 'my property'; this.myMethod = function(){ alert('This is ' + this.myProperty); }; };
The constructor object has its properties and methods defined with the keyword ‘this’ in front of it. Properties/methods have their ‘values’ defined after an equal sign ‘=’. An optional semi-colons ‘;’ at the end of each property/method declaration.
A constructor functions need to be instantiated to use the object as below.
var myNewObject = new myObject(); myNewObject.myMethod();Literal Notation
var myObject = { myProperty : 'my property', myMethod : function(){ alert('This is ' + this.myProperty); } }
The properties/methods have their ‘values’ defined after a colon ‘:’. If you have more than one property or method, they MUST be separated with a comma ‘,’, and they CANNOT have semi-colons after them, otherwise JavaScript will return an error.
A literally notated object simply refered by its variable name as below.
myObject.myMethod();