Javascript Object

An object is a collection of properties. These properties can either be primitive data types, other objects, or functions (which in this case are called methods, but more on this later).

A constructor function (or simply, constructor) is a function used to create an object - this too we'll discuss in detail later.

Javascript comes with many built-in objects, such as the Array, Image and Date objects.

For instance

var Image1 = new Image();

Image1.src = "myDog.gif";

creates a new Image object, and assign a property to the new Image object: the src property. Image1 is a new Image object (an instance of the Image object).

Creating an object in Javascript

//myObject function is a constructor

function myObject(){

}

var myObjectVar = new myObject();

alert(typeof myObjectVar); // displays "object"

The new keyword tells JavaScript to create an object following the blueprint set forth in the myObject() constructor function.

this special variable

Every object method has a variable -

this - which refers to the current instance of that object from which the method is called.

Creating a Property

function myObject(initialvalue){

this.myProperty = initialvalue;

}

var myObjectVar = new myObject("This is a Property");

alert(myObject.myProperty); // displays "This is a Property"

Creating a method

function myMethod(message) {

alert(message);

}

function myObject(initialvalue){

this.myProperty = initialvalue;

this.myMethod=myMethod;

}

var myObjectVar = new myObject("This is a Property");

alert(myObject.myMthod("This is a method")); // displays "This is a Method"

Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working