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 change plugin table structure in WordPress

Some of us will have problem updating or changing your table structure in your WordPress plugin after it has been released to the public. Many people will come up with different ideas to change their existing plugin structure to a new one. Idea such as checking for that particular column existence either through pure SQL or mixture of SQL and PHP. However, the approach here may be a bit overkill. There is a much simpler way.

Mistakes Made By WordPress Developers

In most plugin tutorial on Google, we will see the normal declaration that everyone is familiar.

$table = $wpdb->prefix."hungred_post_thumbnail";
$structure = "CREATE TABLE  `".$table."` (
	hpt_post varchar(255) NOT NULL,
	hpt_name longtext NOT NULL,
	hpt_url longtext NOT NULL,
	hpt_loc longtext NOT NULL,
	UNIQUE KEY id (hpt_post)
);";
$wpdb->query($structure);

This is the usual code instruction during a plugin tutorial. However, the problem with this is that it makes maintenance of plugin difficult. Assuming you are trying to update the table structure with the above statement. You will find difficulty and resort to different means of getting your plugin table structure updated while keeping the same declaration in WordPress. This is not the right way to create a WordPress table!

Powerful way of creating plugin table in WordPress

We need something more powerful to take the job. In WordPress, there is a function dbDelta which will compare the structure between the existing table and the one in the WordPress database. It will automatic update the missing or extra field and alter the table for you. However, this method doesn't exist in WordPress default setup. You will have to import update.php to get this function. Furthermore, dbDelta will required a few criteria to be met before it is usable.

  • You have to put each field on its own line in your SQL statement.
  • You have to have two spaces between the words PRIMARY KEY and the definition of your primary key.
  • You must use the key word KEY rather than its synonym INDEX

Hence, you will have the following declaration.

$table = $wpdb->prefix."hungred_post_thumbnail";
$structure = "CREATE TABLE `".$table."` (
	hpt_post varchar(255) NOT NULL,
	hpt_name longtext NOT NULL,
	hpt_url longtext NOT NULL,
	hpt_loc longtext NOT NULL,
	UNIQUE KEY id (hpt_post)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($structure);

Just that simple. Once you utilized this, changing the structure of your WordPress plugin table will be an ease.

Prevent WordPress Plugin Update From Deleting Important Folder In Your Plugin

Many would know that i have build a powerful thumbnail plugin in WordPress. The plugin work perfectly fine for WordPress 2.8 below but once i updated my WordPress to version 2.8, something bad happen. Every single time whenever i update my WordPress plugin, WordPress will delete the plugin folder with everything included and install the latest plugin version. This post a problem to my plugin since all the images are stored inside the plugin folder. I search online but i couldn't get any help anywhere until i investigate the new version 2.8 core codes.

New Hooks in WordPress 2.8

In WordPress 2.8, it has added a new functionality to delete the previous version of the plugin and then install the latest plugin version into the exact same location. Lucky, it also includes a few more filter hook that did the delete and install process. In class-wp-upgrade.php located at /admin/includes/class-wp-upgrade.php, lines 403-409 you will notice the following few codes,

		add_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'), 10, 2);
		add_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'), 10, 4);
		//'source_selection' => array(&$this, 'source_selection'), //theres a track ticket to move up the directory for zip's which are made a bit differently, useful for non-.org plugins.

		$this->run(array(
					'package' => $r->package,
					'destination' => WP_PLUGIN_DIR,
					'clear_destination' => true,
					'clear_working' => true,
					'hook_extra' => array(
								'plugin' => $plugin
					)
				));

		//Cleanup our hooks, incase something else does a upgrade on this connection.
		remove_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'));
		remove_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'));

I went to search on Google again for these new hook and it seems like there are a couple more of these new hooks being added into WordPress 2.8. But we are particularly interested on 'upgrader_pre_install' and 'upgrader_post_install' filter hook.

Using upgrade_pre_install filter hook

function hpt_copyr($source, $dest)
{
    // Check for symlinks
    if (is_link($source)) {
        return symlink(readlink($source), $dest);
    }

    // Simple copy for a file
    if (is_file($source)) {
        return copy($source, $dest);
    }

    // Make destination directory
    if (!is_dir($dest)) {
        mkdir($dest);
    }

    // Loop through the folder
    $dir = dir($source);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }

        // Deep copy directories
        hpt_copyr("$source/$entry", "$dest/$entry");
    }

    // Clean up
    $dir->close();
    return true;
}
function hpt_backup()
{
	$to = dirname(__FILE__)."/../hpt_images_backup/";
	$from = dirname(__FILE__)."/images/";
	hpt_copyr($from, $to);
}
function hpt_recover()
{
	$from = dirname(__FILE__)."/../hpt_images_backup/";
	$to = dirname(__FILE__)."/images/";
	hpt_copyr($from, $to);
	if (is_dir($from)) {
		hpt_rmdirr($from);#http://putraworks.wordpress.com/2006/02/27/php-delete-a-file-or-a-folder-and-its-contents/
	}
}
add_filter('upgrader_pre_install', 'hpt_backup', 10, 2);
add_filter('upgrader_post_install', 'hpt_recover', 10, 2);

In order to prevent WordPress plugin update from deleting our important folder within our plugin, we must move that particular folder somewhere safe before it starts deleting everything in our plugin. After the update has completed, we will then move the folder that we want to preserved and overwrite any existing files in that folder. We can't remove the filter action as shown on the core WordPress code was because the filter was not added previously. Thus, removing the filter will not prevent the deletion.

SWFUpload Upload Error: 500 Problem

Recently i got a client who wanted me to build a custom multiple upload function with SWFUpload into Amazon S3. There is a small introduction in case you have no idea what is SWFUpload or you want to build one up yourself, you can visit Tutorial: Cross browser Multiple Uploader With SWFUpload And JavaScript. After testing etc. everything went smoothly on my side until the program is being integrated into his server. Upload Error: 500 was appearing and causes the upload to fail.

The Problem

The problem is with flash 10 that seems to be incompatible with mod_security. This caused the flash player to fail which result in an Upload Error: 500 on SWFUpload. The other thing that also might caused it to display Upload Error: 500 was the file limit set on the server.

The Solution

Did a few search on Google and the most helpful link i found was actually in the SWFUpload forum,

Upload error 500| SWFUPload

There are a few ways to solve this problem but all of them are pointing at fixing up the server. You guys can try the following ways to fix up this problem.

1. This is what my client host service done on their server. They off the following things in their server.

SecRuleEngine Off
SecRequestBodyAccess Off

2. turn up the upload size of your web server.

<ifmodule mod_php5.c>
php_value upload_max_filesize 100M
php_value post_max_size 100M
</ifmodule>

3. You may also want to add these settings on your .htacess file. Although these doesn't work for my client but it does work for some of the people out there.

SecFilterEngine Off
SecFilterScanPOST Off 

4. Sometimes size limit also gives you problem so you may want to try increase the size on your php.ini

upload_max_filesize=200M
post_max_size=200M

5. Turn off mod_security which might not be a good idea.
6. Direct your files into Amazon S3 to solve server issues

Tutorial: How to get image path on a post in WordPress efficiently

This is something that WordPress currently doesn't support yet. You will face the problem of retrieving image on a particular post on the loop while you are working on WordPress theme or plugin. WordPress doesn't provides you with a method that you can use to retrieve the images on the post and you would have to search all over the internet to find someone sharing their secret with you. Thus, rather than using a complex or methods built by others, i personally have a much simple and efficient way of doing this.

The Problem

I wanted to retrieve all images on a particular post under a category and make it into a gallery. However, WordPress doesn't provides such method. Furthermore, the methods provide by others seems to complex this particular function. I want a simple and efficient way of doing this. Not a redundant one.

The Solution

The best way is to look into the core of PHP and search for a particular function that do this automatically. I search quite long and finally found preg_match_all from PHP core build. However, it return the number of match element instead of the result of the URL! But if you read closely it can also retrieve the matched result. So, how do you retrieve the images? Answer is regular expression! What i did was as follow,

$content = get_the_content();
preg_match_all('/src=\"https?:\/\/[\S\w]+\"/i', $content, $matches, PREG_SET_ORDER);
foreach($matches as $e)
{
	echo '<div class="slideshow_box"><img width="106px" '.$e[0].'/></div>';
}

Basically, i retrieve the content using WordPress method 'get_the_content()'. Using the preg_match_all PHP function i placed a regular expression that will retrieve all string that start with 'src="' and end with a single '"' quote symbol. You can read more on regular expression on Google (although until now i still can't find a real good reference). it will return the number of match result normally but with the additional variable, $matches which store all matched string, we can easily get all images on a post in WordPress without building additional big function to do this. You can remove 'src=' to retrieve something like 'www.hungred.com' instead of 'src="www.hungred.com' but if you know regular expression better than i do, this will easily be a piece of cake for you.

The Conclusion

This may seems to be an obvious thing to do. But you may be surprise after doing some Google search that many people actually built up function just to accomplished this and no one is sharing such sweet method with you! This is just to write out to help others who are still searching for a better solution than looking at complex method created by others. Hope it help.