The Predefined Prototype Object In JavaScript

Most of us learn JavaScript from tutorial website such as w3schools or tizag.com. However, these tutorial site only covered the most fundamental of JavaScript. Many hidden features of JavaScript are usual removed to simplify the tutorial. Although basic does bring us a long way, we still need to read more of these features eventually and improve our coding. In this article, i will cover the predefined prototype object in JavaScript. We will discuss everything we need to know about prototype object and the application in the real world.

The Prototype Object

The prototype object was introduced on JavaScript 1.1 onwards to simplify the process of adding or extending custom properties and methods to ALL instances of an object. In other word, prototype object is used to add or extend object properties or methods so every other object will also have such properties/methods. Let me show you an example. Below listed a few way to extend an object properties.

//adding a custom property to a prebuilt object
var imgObj =new Image();
imgObj.defaultHeight= "150px";

//adding a custom property to the custom object "Shape"
function Shape(){
}
var rectangle =new Shape()
rectangle.defaultColor = 'blue';

From the above example, we are able to extend properties of each object easily. However, if i create a new instances of the same object, the properties will be lost!

var newImg =new Image();
alert(newImg.defaultHeight); //return undefined 'defaultHeight';

var newRec =new Shape()
alert(newRec.defaultColor); //return undefined 'defaultColor';

This is when prototype object comes in. Prototype object is able to add the properties above and extend to other new instances object as well. Hence, the following will allowed all new instances created to contain the properties or methods attached by any previous object. We just have to add the keyword prototype between the object and name of the properties/method to use the prototype object. Using the same example above,

//adding a custom property to a prebuilt object
function check_height(){
 return typeof this.defaultHeight != 'undefined'?true:false;
}
var imgObj =new Image();
imgObj.prototype.defaultHeight= "150px";
imgObj.prototype.hasHeight= check_height;

//adding a custom property to the custom object "Shape"
function Shape(){
}
function color_checker(){
 return typeof this.defaultColor != 'undefined'?true:false;
}
var rectangle =new Shape()
rectangle.prototype.defaultColor = 'blue';
rectangle.prototype.hasColor = color_checker;

var newShape =new Shape()
alert(newShape.defaultColor) // blue
alert(newShape.hasHeight) // true

var newImg =new Image()
alert(newImg.defaultHeight) // 150px
alert(newImg.hasColor()) // true

Now every new instances of Image and Shape will have the properties and methods defined previously by the variables rectangle and imgObj.

Prototype Object Restriction

Prototype object can add or extend properties or methods to any custom object but for predefined object, only those that are created with the new keyword are allowed to use the prototype object in JavaScript. The following list some of these predefined object.

  • The date object
  • The string object
  • The Array object
  • The image object

Prototype Object is an Array

In case you haven't notice, prototype object is actually an array. From all of the above example, we are doing the following declaration to create new properties or method

//declare a function
obj.prototype.name = function(){};
//declare a property
obj.prototype.name = variables;

Notice that we are actually associating a name with a variable or function into the prototype object. Hence, we can also declare prototype with the same way as declaring an array.

obj.prototype ={
name: variables,
name: function(){}
}

The above two methods are similar and can be declare either way. Since both ways are similar, performance wise shouldn't make any big differences.

Priority Between Prototype And Own Property

What if we have both property? If the object itself already has a prototype property and if we redeclare the exact same property again without the keyword prototype, JavaScript will take which property? The answer is own property. In JavaScript, the own property takes precedence over the prototype's. Consider the following example,

function Rectangle(w,h){
	this.area = w*h;
}
var obj = new Rectangle(2,2); //area is 4;
obj.prototype.area = 200; // now we have own and prototype 'area'
alert(obj.area); // 4 will appear instead of 200; Hence, own property takes priority first.

What happened if we delete the property?

delete obj.area
alert(obj.area); // 200 appeared! 

Prototype property will take over again. Hence, we can use the Own property to overwrite prototype property defined in the object.

Identify Own and Prototype Properties

How do we identify whether the given object properties are from own or prototype? In JavaScript, there is a method hasOwnProperty which can be used to identify whether a given property is from own or prototype. Let's look at the following example,

function Rectangle(w,h){
	this.area = w*h;
	this.parameter = w+h;
}
obj.prototype.height = 5; 
obj.prototype.weight = 6; 

var obj = new Rectangle(2,2); 
obj.hasOwnProperty('area');// return true;
obj.hasOwnProperty('parameter');// return true;
obj.hasOwnProperty('height');// return false;
obj.hasOwnProperty('weight');// return false;

Inheritance Using Prototype Object

In the real world, prototype object is usually used as inheritance during OOP (Object Oriented Principle) with JavaScript. In JavaScript, we are not looking at classes inheriting other classes but object inheriting other object since everything in JavaScript is Object. Once we understand this, it will be easier for us to show inheritance example with prototype object.

function Shape(){
}
function color_checker(){
 return typeof this.defaultColor != 'undefined'?true:false;
}
function getArea(){
return this.area;
}

Shape.prototype.defaultColor = 'blue';
Shape.prototype.hasColor = color_checker;
Shape.prototype.getArea = getArea;

function Rectangle(w,h)
{
	this.area = w*h;
}

function Rectangle_getArea()
{
    alert( 'Rectangle area is = '+this.area );
}
Rectangle.prototype = new Shape();
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.getArea  = Rectangle_getArea; 

Using the custom object 'Shape' example above, i extend it so that 'Rectangle' will inherit all method and properties of 'Shape'. Inherit can be done through this sentence

Rectangle.prototype = new Shape();

'Rectangle' prototypes are assigned to the prototype of the 'Shape' through an object instance thereby "inheriting" the methods assigned to the prototype array of 'Shape'. After 'Rectangle' has inherit 'Shape', it overwrites the getArea method of 'Shape' through this statement.

Rectangle.prototype. getArea  = Rectangle_getArea; 

Inheritance using prototype object can reduce a lot of unnecessary coding and make your overall code run faster. The constructor on the above code is to overwrite the way Rectangle object is being instantaneous since the Rectangle prototype was overwritten by Shape prototype on the previous statement. Hence, to create a Rectangle object, the constructor for it will be as follow

function Rectangle(w,h)

We can use the above code as follow

var recObj = new Rectangle(20, 20);
rec.getArea(); //return 'Rectangle area is = 400'
rec.hasColor(); // return true;
rec.defaultColor;//return blue;

Check Prototype Inheritance

We can check whether a particular object is another prototype object by using the function isPrototypeOf. In other word, we can check whether a particular object inherit another object properties and methods. Using the previous inheritance explanation, we can check whether Shape is inherited into Rectangle object.

var rec = new Rectangle(5,5);
Shape.isPrototypeOf(rec);// return true;

This shows that Shape is a prototype of rec object. I think the method name said it all.

Tutorial: How To Sort An Array In JavaScript

In JavaScript, we are given a method Sort() to perform sorting. Although Sort() is said to be used for sorting an array, it can also be used to sort anything other than an array itself. In this article we will discuss all about JavaScript array.

Sort() in JavaScript

By default, the method Sort() in JavaScript takes a given array and sort it in lexicographical order and not alphabetical order! This means that the Sort() method sort a given array in dictionary order. Let's consider the following example of Sort method.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]

The above look fine when sorting an array of string but when it comes to number we will face a little problem.

var list =[ 39, 108, 21, 55, 18, 9]
list.sort() //[108, 18, 21, 39, 55, 9]

Looking at the result of the sort function seems to be unsorted but the fact that it is sorted according to lexicographical order does makes it in an ordered form after using the default sort method. Lucky, JavaScript doesn't force you to follow lexicographic order. You may also define a function to sort them in your own way.

Reverse Sort()

We get our result in lexicographical order after we performed a Sort() function. What if we want the reverse order of the sort function instead? In JavaScript, there is a function Reverse() which can help us to reverse the result of the array in the opposite order of the result. Consider the following example to illustrate Reverse() method in JavaScript.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]
list.reverse() //["Monkey", "Zebra", "Donkey"]

Simple and powerful.

Customize Sort

The default Sort() function in JavaScript is quite simple and clear. Now, we will look at how we can customize this sort function. JavaScript Sort function does take in a parameter which is a function. Short to say, Sort() Method will sort your array instructed in the given function. However, the return value of the function must be as follow,

  • returns a value less than 0: parameter 'a' value is less than parameter 'b' value. 'a' come BEFORE 'b'.
  • returns a value greater than 0: parameter 'a' value is more than parameter 'b' value. 'a' come AFTER 'b'
  • returns exactly 0: parameter 'a' and 'b' have the same value. no change.

With the above rule, we can create a function that sort our array in numerical order instead of lexicographic order.

function sortmyway(data_A, data_B)
{
	if ( data_A < data_B ) // data_A come before data_B
		return -1;
	if ( data_A > data_B ) // data_A come After data_B
		return 1;
	return 0; // data_A == data_B, no change.

}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

The above example look good but the function seems to be a bit lengthy. You can change the comparison statement in a shorter form using the '?' symbol and we will get a shorter version of the code above.

function sortmyway(data_A, data_B)
{
return ((data_A < data_B) ? -1 : ((data_A > data_B) ? 1 : 0));
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

We can even shorten the above declaration to perform the same task as shown below,

function sortmyway(data_A, data_B)
{
	return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]

All the methods above sort the array in ascending order.

Sort Descending order

Using the shortest method i have above, i can declare a sorting function which sort in descending order as follow,

function sortmyway(data_A, data_B)
{
	return (data_B - data_A);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[108, 55, 39, 21, 18, 9]

You can also achieve this by using the Reverse() method to eliminate the need to declare two sort function for ascending and descending order.

Random Sort Array

Well, we can also take advantage of the sort function to randomize our array. This way, we do not have to perform any loop which also contribute to function efficiency.

function sortmyway(data_A, data_B)
{
	return 0.5 - Math.random(); //random gives us result between 0 and 1
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[21, 9, 39, 108, 18, 55]

Summary

Other than array, we can also sort unordered and ordered list. Sort() method in JavaScript can help us perform different kind of sorting in every type of element not restricting to array only. However, using JavaScript to perform sort of other element other than array can be a lot of pain. Personal advice is to use JavaScript framework such as jQuery or Mootools to ease the job. On the other hand, Sort() method can also be used to substitute unnecessary loop to create a more efficient code especially when comparing each element in an array is required. (we just have to eliminate the return value to perform such task) . Even eliminating duplication in an array is possible with Sort() method!

The Secret Arguments Array in JavaScript

Well, this is not really a secret to be exact. Many experience programmers who have worked with JavaScript for many years will surely come across arguments array. Some book may even forgotten the existence of arguments array since it is not widely used. Hence, i believe majority of JavaScript programmers do not actually know the existence of such array in JavaScript. So allow me to explain what is arguments array.

Arguments Array

An arguments array is a predefined array used within a function in JavaScript. Whether you used it or not it will still exist within that function. The main advantage of using arguments array is the unlimited number of argument or parameter you can pass into a function. Let's consider the following example,

function example()
{
	var sum = 0;
	for(i = 0; i < arguments.length;i++)
	{
		sum += arguments[i];
	}
	alert(sum); //45
}
example(1,2,3,4,5,6,7,8,9,0);

i find that the above example will simply get the idea through how arguments array worked. It is an array so whatever we passed in via arguments will be placed into an arguments array within the function. Then, we simple just used it. The above example is an simple addition function. You can see another example at override ‘this’ object in JavaScript

Detect Arguments

What if we want to use the arguments array in certain circumstances but not all the times? Preload with jQuery shows one particular function that uses an array or parameter depend on how users want to use that function (now, you might have guess how a library such as jQuery allows multiple different parameter for a single function). In order to do that, we have to detect what arguments or values been passed on to the function.

In JavaScript, we can detect a particular value by using comparison operators (===, ==, !=, etc.) but there are also other techniques to detect these arguments. We can use in operator which detect whether a given value is in the arguments array (in operator is not widely supported. Thus, you don't see many using it). There are also typeOf operator which determine what is the type of the value (string, object, int, etc.)which you can see from Preload with jQuery article. Lastly, there is Autocasting operator which evaluate whether a variable has a value (NaN, 0, false, undefined, null, or an empty string are considered as no value). Let's look at each new detection method example that i mention here.

//Detect whether there is a "hello" member in the arguments array: 
var parameter = 'hello' in arguments? arguments : "";

//Detect whether arguments contains at least one argument
var parameter = typeof arguments[0] != 'undefined'? arguments : "";

//Detect whether the user passed an object(can be array) or a list of arguments
var parameter = (typeof arguments[0] == 'object')? arguments[0] : arguments;

//Detect whether there is an arguments passed into the function and assign the number of arguments into the variable
var parameter = arguments.length || "";

Summary

Using Argument Array is great as we are not restricted by the number of parameter on a given function. However, many online tutorial on basic JavaScript no longer practice this since it is said that this has been depreciated with new browsers emerged but its still usable in JavaScript up till today (who said its depreciated!).

Tutorial: How to override ‘this’ object in JavaScript

Have you ever experience a time when the calling object 'this' needed to be override and somehow you just couldn't do that? You tried left hand assignment but it just won't work? wondering how can 'this' object be overridden in JavaScript but can't find the correct answer on Google? This article will explain how this can be done.

Left hand assignment

Ever tried left hand assignment to override 'this' object?

var obj = document.getElementById("button");
this = obj

It will fail and gives you 'invalid assignment left-hand side'.

Using Call() to override 'this' object

There is a function in JavaScript, Call() which can help you override 'this' object or specify the 'this' object. Let's consider the following example,

function example(a,b)
{
	this.value == 'button'?alert(a):alert(b);
}
var textobj = document.getElementById('input_relink');
example.call(textobj, 'It is a button!', 'It is not a button');

We look at a text box and check whether the user key in 'button'. But we uses 'this' object to verify the input text in the function example which takes in two parameter as shown above. The Call() method is used whenever you wish to override 'this' object which is placed at the first parameter and the rest of the parameter will be exactly the same as the method parameter. Hence, we used the function in this way for the above example because it has two parameter.

//override 'this' with object 'textobj'
example.call(textobj, 'It is a button!', 'It is not a button');

If we have another function which takes in 3 parameter, we will do this.

function example(a,b, c)
{
	this.value == 'button'?alert(a):alert(b);
	alert(c);
}
var textobj = document.getElementById('input_relink');
example.call(textobj, 'It is a button!', 'It is not a button', 'Completed');

You can also used it without parameter like the one illustrated below,

var o = { x: 15 };
function f()
{
    alert(this.x);
}
f.call(o);

Using Call() method restrict your variable given on the method. On the other hand, we can use another method Apply() which override the 'this' object giving the second parameter as an array.

Using Apply() method to override 'this' object

The difference between call and apply method is the parameter needed to use them. For Call() method it depends on the parameter of the function as shown above. But for Apply() method it can have more than the amount of parameter in the function (since it takes in an array). Similarly, the first parameter of both methods are used to override 'this' object. Let's consider the following example,

var o = { x: 8 };
function example()
{          
    // arguments[0] == object 
	var sum = 0;
    for(var i = 1; i < arguments.length; i++)
    {
       sum+=arguments[i]
    }
	alert(sum+ this.x);
}
example.apply(o, 1, 2, 3, 4)

I am using the depreciated argument array to look through the argument being passed into the function, sum them up, alert to the user. Similarly, i can do this using an array.

var o = { x: 8 };
function example(a, b, c)
{          
	alert(this.x+a+b+c);
}
example.apply(o, [1,2,3])

Pretty simple isn't it?

Tutorial: Function within a function in JavaScript

Do you know that you can define a function within a function in JavaScript? Furthermore, these functions defined in the outer function are not accessible outside the scope unless you expose them to the outside scope? This is pretty interesting since basic web tutorial doesn't really cover function in a function with JavaScript. Function in a function are only noticeable when you come across or read about in the real world of JavaScript application.

Function within a function

How do you define a function within a function in JavaScript? Pretty simple and straight forward actually. Just throw another function into the function. This will caused the inner function to be accessible only within the scope of outer function.

function outer_func(){
	function inner_func(){
		alert('hellow');
	}
	//hellow will be alert
	inner_func();
}

If you try to access the inner function, an undefined error will occurs. On the other hand, using the outer function still permits.

//undefined function
inner_func();
//alert 'hellow'
outer_func();

Access the inner functions

Sometimes we want some methods in the outer function to be accessible. We will have to return an object with the relevant method attached to it for it to be accessible outside the scope.

function outer_func(){
	var newObj = new Object() 
	function inner_func(){
		alert('hellow');
	}
	function inner_func2(){
		alert('RAWR!');
	}
	newObj.inner_func = inner_func;
	return newObj;
}

Above, we created two function and only attached the first function into the return object. Thus, calling the second function will fail.

var func_Obj = new outer_func();
// alert 'hellow'
func_Obj.inner_func();
//undefined
func_Obj.inner_func2();

Some Real World Application

Function within a function act as a security measure for certain action to be restricted outside the scope. Open source code tend to use this to prevent certain dependency methods from being access. Performing certain organization through this method was also applied in real life application.