Saturday, March 26, 2011

javascript object oriented programming 1:create objects

how to create objects One way to create an object:
var ship = {
     wings: 'wings',
     body: 'body',
     jet: 'jet',
     guns: 'guns'
};
Now, we have a ship object. This object has 4 properties:wings,body,jet,guns. An object property can contain a function, we call it a method.
var ship = {
     wings: 'wings',
     body: 'body',
     jet: 'jet',
     guns: 'guns',
     fire = function () {
         return 'start to fire';
     }
};
Now our ship object has a method fire. Accessing Object's properties We can access an object's properties by using either square bracket notation or dot notation. For example: ship.wings or ship['wings']. Dot notation is easier to read and write. Accessing a non-existing property returns 'undefined': ship.tail. Calling Object's methods ship.fire() invokes the fire function and returns the value 'start to fire'. Calling a non-existing method causes error: ship.move(). Using keyword 'this' Let 's add a method to our ship.
var ship = {
     wings: 'wings',
     body: 'body',
     jet: 'jet',
     guns: 'guns',
     fire = function () {
         return 'start to fire';
     }
     getGuns = function() {
         return this.guns;
     }
};
'this' actually refers to this object or current object. Another way to create objects is to use constructor function. This way is actually more familiar to people with java or php5 background.
function Ship(model) {
 this.model = model;
 this.wings = 'the wings';
 this.body  = 'the body';
 this.jet   = 'the jet';
 this.guns  = 'the guns';
 this.fire  = function() {
  return this.guns + ' start to fire';
 };
 this.getModel = function(){return this.model};
}
var shipOne = new Ship(1);
var shipTwo = new Ship(2);
We can also create a new object in this way, although it looks a little wierd:
var shipOne = new Ship(1);
var shipTwo = new shipOne.constructor(2);
This works because constructor property refers to a function and we can call this function to return a new object. We use instanceof to tell an object's type: if (shipTwo instanceof Ship){}; In javascript, object is passed by reference, same to most of other OOP langauges. Global Object In javascript, the host environment provides a global object and all global variables are actually properties of the global object. If your host environment is the web browser, the global object is called window.

No comments: