Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, February 21, 2013

Objects in JavaScript

In JavaScript all objects are equal by nature. This means that

  • There is no class difference in JavaScript objects.  They are just objects and there is no class birth mark with them.   In Java any object must belong to one class and it will always be so in its life cycle.  
  • JavaScript objects can change themselves dynamically.   

Conceptually JavaScript object is the container of properties which are the name-value pair.  The property value can be the primitive values, or other object(including the functions because they are also objects).  Physically object is the structure that hold these properties of the object.

Creation of Object


So how a JavaScript come into life? There are several ways to do so. One normal way is using constructor function. What is constructor function?  Constructor function is a normal function but it is invoked with the keyword new.    It is kind of magic.   When the function is invoked in such way three things will happen within the function: An object is created, this is resolved for this new created object and the new object is returned even you don't do so explicitly in the function. The below are two examples that use constructor functions to create a Car object.   One is with named function and another with anonymous function. The results are the same.
function Car(model, make, year) {
 this.make = make;
 this.model = model;
 this.year = year;
}
var myCar1 = new Car('Honda', 'Accord', 2010);

var Car = function (model, make, year) {
 this.make = make;
 this.model = model;
 this.year = year;
}

var myCar2 = new Car('Honda', 'Accord', 2010);

But when this function is invoked without the keyword new.   The magic of object creation will not happen. 

All objects in JavaScript are created with constructor function.  With an object you can check its constructor function using the below statement

myObj.constructor

It will return the constructor function used to create the object.  In above examples myCar1.constructor will return Car() function and myCar2 will return anonymous function.


Apart from using constructor function to create objects, JavaScript provides another way or shortcut to create the objects: Literal.   The below are two examples of using literal to create objects.

var myCarLiteral = { make:'Honda',
                     model: 'Accord',
                     year: 2013}; 
Actually these creation are the same as we use the constructor functions.  But if you check the constructor function of this object you will find that it is function Object().


Operators Used to Check the Type of Objects


There are two operators that can be used to check the type of the objects: typeof and instanceof.
typeof operator is used to return the type of object. It wil return the string that is the name of object type.  For all objects it will return object. 
 instanceof is used to decide if an object is created from one constructor function.  It will return a boolean value. 
 function Car(model, make, year) {
  this.make = make;
  this.model = model;
  this.year = year;
 }
 var myCar1 = new Car('Honda', 'Accord', 2010);

 var myCar3 = { make:'Honda',
       model: 'Accord',
       year: 2013};

 console.log(myCar1 instanceof Car);
 console.log(myCar3 instanceof Object);
 console.log(typeof Car);
 console.log(typeof myCar1);
 console.log(typeof myCar3);

The above log output will be: true, true, function, object, object.


Built-in Objects or Native Objects


The above examples arex custom-made constructor function.  Actually JavaScript provides many built-in constructor functions already.   These are: Object(),Number(),String(),Array(),Function(),Date(),RegExp(),Error(). In these the most interesting one is Object().   This is the root of all JavaScript objects.

Here we can use Obect() to create myCar object which we create using custom constructor function.

var myCar = new Object(); 
myCar.make = "Honda";
myCar.model = "Accord";
myCar.yaer = 2013;
Here this myCar object actually is the same as myCar using Car constructor function even the constructor functions they use are different.     But obviously the customer constructor function is more convenient in creating multiple instances sharing the same properties of Car.

Saturday, February 2, 2013

JavaScript as Object-Oriented Language


As some of experienced Java, C++ or C# programmers I used to think JavaScript as some kind of elementary programming languages when compared to the full-fledged OO languages such as Java or C#, or C++. However even JavaScript cannot do some advanced and complex things which we can do using Java, C# or C++ it is still an programming language with OO features. And programmers normally are so used to class-type OO languages - Java, C++ or C# they would find it hard to understand and confusing how to use the OO features in JavaScript. The below is aimed to help skilled Java, C++ or C# programmer to grab the essence of JavaScript OO features in short time.


Object concepts in JavaScript


Contrary to the impression of me and some of Java developers, JavaScript thinks heavily with object. Almost everything in JavaScript is object. At the first glance it is not so obvious because JavaScript doesn't explicitly show this like Java, C++, C#. But it is true that most of things are dealt with objects in JavaScript. A number, a string, a date, an array, a function or a custom-made object are all objects even with some primitive type like numbers.

var myAmount = 123.456;
var myAmount = new Number(123.456);

In above example the first line will declare one variable myAmount with the given value. Actually JavaScript will create one Number object. It is the same as the second line does.
The meaning of object in JavaScript is the same as in Java, C++, or C#. An object is a collection of data stored as properties and the methods that can be used to manipulate the data in the object.
The below example demonstrate the properties and the methods of JavaScript object. In the first line we declare one string object with the value as "This is a string" and the second line the property length of this string object is used. And in third line we invoke a method called toUpperCase of the string object.


var myString = "This is a string";
alert(myString.length)
var upperCasedVar = myString.toUpperCase();
 

So far the object in JavaScript looks very similar as Java, C++ or C# although object creation in JavaScript sometimes is not so obvious.

 

What does object in JavaScript look like?


 

Objects in JavaScript have properties and methods. The properties are the name-value pairs and method. These are exactly same as Java, C# or C++.
But there are something different in JavaScript. Java, C++ or C# are all class-based Object-Oriented languages. All properties and methods must be predefined in the class from which the object is instantiated. In JavaScript you can don't need to predefine them. All you need to do is to add the property name to the object and then give the value to this property. That's it.


var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.model = "Inspiron";
myLaptop.year = 2011;
 

In the above example we create one object as myLaptop and then we add three properties to this myLaptop object.
For the properties in JavaScript object there is one thing which cannot be done in Java or other OO languages: You can delete one property from the object using keyword delete.
//Creates a new object, myobj, with 4 properties.
var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.model = "Inspiron";
myLaptop.year = 2011;
myLaptop.uer = "Mark Chen";

//Removes the a property, leaving myLaptop with only 3 properties.
delete myLaptop.user;

 

Methods in JavaScript is similar to the properties. Methods of JavaScript object are the normal JavaScript functions which are assigned to the properties of the object.
The below example shows that one function is defined and assigned to the object: myLaptop. It becomes the method of that object and you invoke this method in this object.
var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.startup = function() {
      return "Startup is done....";
};
myLaptop.startup();
document.write(myLaptop.make + "  " + myLaptop.startup());

 

How do you create object in JavaScript?


 

JavaScript provides some built-in objects. String, Date, Array, Math and Object are mostly common used. You can also have the custom-built objects.
There are many ways in JavaScript to create an object. Actually we have seen two different ways to create objects in the above examples: using new operator and using object initializer.
The below are some examples of creating JavaScript objects using new operator and object initializer.
var myDate = new Date(2013, 2, 11);

var myObj = new Object();

var anotherObj = {};

var myLaptop = new Object();
myLaptop.make = "DELL";
myLaptop.model = "INSPRION";
myLaptop.price = 1150.00;

var anotherLaptop = {make: "DELL", model:"INSPRION", price:1150.00}

 

Besides the new operator and object initializer you can also use constructor function. This way is very similar to Java, C# or C++. Constructor function is a JavaScript function which is used to set the properties and methods for the object. You can use new operator to invoke this function. What you get is a JavaScript object.
function Laptop(make, model, price) {
    this.make = make;
    this.model = model;
    this.price = price;
    this.startup = function() {
        alert(make+" "+model+" is started up.");
    }
}

var myLaptop = new Laptop("DELL", "INSPRION", 1150.00);


Inheritance and Prototype


Inheritance is one of most important characteristics of OO language. In class-based OO languages such as Java, C++ or C# inheritance is implemented using class and subclass. JavaScript also provides inheritance. But it is implemented using another concept called prototype.

So what is prototype in JavaScript? A prototype is a property in an object and this property actually is a reference to another object. But this prototype property is a bit special: the object will inherit all properties and methods from its prototype object.
The below is an example of using prototype to add one property and one method to an object.


function Laptop(make, model, price) {
    this.make = make;
    this.model = model;
    this.price = price;

}

// Adding the property to the prototype of Laptop object
// Adding the method to the prototype of Laptop object
Laptop.prototype.user = "Mark";
Laptop.prototype.startup = function() {
      alert(this.make+" "+this.model+" "+this.user + " is started up.");
}
     
var myLaptop = new Laptop("DELL", "INSPRION", 1150.00);

// Invoke the startup method which is inherited from prototype
myLaptop.startup();

 

The prototype property in JavaScript object is just another object. When you invoke new operator against Laptop function. The object which is created will automatically has one prototype property set as one empty object. But you can override this empty object with the object you want. In the below example the prototype of Laptop is set to Computer object. So all Laptop objects will have the properties and methods of Computer object.


function Computer(user) {
      this.user = "Mark";
      this.startup = function() {
            alert(this.user + " is started up.");
      }
}

function Laptop(make, model, price) {
    this.make = make;
    this.model = model;
    this.price = price;
}

Laptop.prototype = new Computer("Mark");
     
var myLaptop = new Laptop("DELL", "INSPRION", 1150.00);

myLaptop.startup();