Simple Inheritance In Javascript: The Traditional Way

Getting your head wrapped around inheritance can be one of the more tricky things for a new javascript developer. Not only does javascript have this quirky thing called a prototype object, there are many ways to use it actually implement some form of inheritance.

There has been a lot of desire by some (and subsequent abstractions) to make javascript inheritance act more like it would in a classical language.  One of the most famous being the “Class” abstraction by John Resig.

In fact, the desire is so strong it looks like the notion of “classes” is coming to the javascript language itself in the not so distant future.

But the important thing to understand is, even when that day comes, prototypal inheritance won’t go away.  It will always be there under the hood and the notion of “classes” will really just be some nice syntactical sugar on top of the prototypal inheritance we know and love (or loathe depending on your viewpoint) today.

Personally,  I think knowing and understanding javascript prototypes and how they are used for inheritance in a more traditional sense is an important foundation for every javascript developer. Class abstractions to this point, provide something similar to what is found in some other languages, but it’s not exactly the same.

For example, check out this peculiarity. Properties set on a prototype are references shared by all instances, so changing a prototype property on one instance would change the value for all instances!

If that doesn’t quite make sense. Watch this. Say you use a class abstraction. In this case we’ll use the John Resig example. You can get in a lot of trouble if you set a “class” property to an array (Note the parents property)…


var Baby = Class.extend({

  parents: [],

  init: function(mom,dad){
    this.parents.push(mom);
    this.parents.push(dad);
  }

});

var girl = new Baby('Mary', 'John');

console.info(girl.parents); // "Mary", "John" ... okay so far...

var boy = new Baby('Jill', 'Jack');

console.info(boy.parents) // "Mary", "John", "Jill", "Jack" ... What!?
console.info(girl.parents) // "Mary", "John", "Jill", "Jack"... What!?

Coming from a background with a classical language (like PHP in my case) this might confuse you at first. It certainly did for me. Once you understand how the prototype object actually works though, it makes sense. What’s going on in the background? Something along the lines of this…


function Baby(mom, dad) {
    this.parents.push(mom);
    this.parents.push(dad);
}

Baby.prototype.parents = [];

var girl = new Baby('Mary', 'John');

console.info(girl.parents); // "Mary", "John" ... okay so far...

var boy = new Baby('Jill', 'Jack');

console.info(boy.parents) // "Mary", "John", "Jill", "Jack" ... What!?
console.info(girl.parents) // "Mary", "John", "Jill", "Jack"... What!?

Since the prototype is a shared reference, the solution is to assign the parents array as a property of the instance and not the prototype itself.


var Baby = Class.extend({

  init: function(mom,dad){

    this.parents = [];

    this.parents.push(mom);
    this.parents.push(dad);
  }

});

var girl = new Baby('Mary', 'John');

console.info(girl.parents); // "Mary", "John" ... okay so far...

var boy = new Baby('Jill', 'Jack');

console.info(boy.parents) // "Jill", "Jack" ... looks good...
console.info(girl.parents) // "Mary", "John"... the world is sane again...

Or without the class abstraction…


function Baby(mom, dad) {

    this.parents = [];

    this.parents.push(mom);
    this.parents.push(dad);
}

var girl = new Baby('Mary', 'John');

console.info(girl.parents); // "Mary", "John" ... okay so far...

var boy = new Baby('Jill', 'Jack');

console.info(boy.parents) // "Jill", "Jack" ... looks good...
console.info(girl.parents) // "Mary", "John"... the world is sane again...

I think the important thing to understand here is that a prototype != class.

Subtle differences like this (and I’m sure there are many others) make things really confusing if you don’t understand what is going on beneath the surface of a class abstraction.

For that reason, and because I like using the language more in the way it was originally intended, I currently implement inheritance in the traditional way: with prototypes and constructors.

Now don’t get me wrong, it’s more verbose and has some oddities, but when classes eventually arrive in the language and are fully adopted, I’ll be in a much better position to deal with the “quirkiness” because I’ll still think of it conceptually in terms of prototypes and prototypal inheritance. 

So with that said, here’s the blueprint for the “traditional” way of implementing inheritance in javascript….


// Animal Constructor
function Animal(name) {

   this.name = name;
   console.info("Hi my name is " + this.name + ". I'm an animal.");

}

// Animal Prototype
Animal.prototype.move = function(x, y) {

     /* Do stuff with x and y*/

     console.info("I'm a moving animal.");
};

// Dog Constructor
function Dog(name) {

    Animal.call(this, name); // Call the animal "super" constructor

    console.info("And I'm also a dog.");
}

// Important Inheritance Stuff
Dog.prototype = Object.create(Animal.prototype); // Dog "Inherits" From The Animal Prototype
Dog.prototype.constructor = Dog; // The reference to the constructor in Dog must be set manually

// Dog Prototype
Dog.prototype.move = function(x,y) {

     Animal.prototype.move.call(this,x,y); // Call the "super" Animal method if you want

     /* Do more stuff with x and y*/

      console.info("And Guess what? I'm also a moving dog too.");
}

// Or add some brand new methods to Dog
Dog.prototype.bark = function() {

      console.info("Watch out! I bite.");

}

And here’s how it looks when it’s used…


var buster = new Animal('Buster'); // Hi my name is Buster. I'm an animal.
buster.move(10,10); // I'm a moving animal.

var fido = new Dog('Fido') // Hi my name is Fido. I'm an animal. And I'm also a dog.
fido.move(10,10); // I'm a moving animal. And Guess what? I'm also a moving dog too.
fido.bark(); // Watch out! I bite.

You may be thinking this looks crazy. But it’s not that hard once you understand what’s going on. The important lines in all this are …

// Important Inheritance Stuff
Dog.prototype = Object.create(Animal.prototype); // Dog "Inherits" From The Animal Prototype
Dog.prototype.constructor = Dog; // The reference to the constructor in Dog must be set manually

The Dog prototype is assigned to a copy of the Animal Prototype using Object.create (see footnote on this below). Then because the constructor still points to the Animal constructor function in the new Dog prototype, we must manually set the reference to the Dog constructor.

The other important lines to make mental note of are how to call the overriden parent via direct reference both in the Dog constructor…

  Animal.call(this, name); // Call the animal "super" constructor

and in any Dog prototype methods…

 Animal.prototype.move.call(this, x, y); // Call the "super" Animal method if you want

Keep in mind for an actual project, I’d highly recommend using a module loader like requireJS. The module loader will help not only with breaking the inheritance chain into digestible chunks, but with the direct references that are needed by the child object to reference its parent methods. In a follow-up post I’ll take this exact example and show you how it would be used inside a real requireJS project.

Although the example may look scary, once you start using it in an actual project it’s not that bad. Most importantly, if you start doing it this way you get the very important benefit of really understanding how prototypal inheritance actually works!

A note on Object.create and EMCAScript5:

Object.create is a new feature of ECMAScript 5 which allows for a new, easier way to create an object from another object’s prototype. It’s not available for some older browsers, but there is a simple polyfill available.

But the polyfill doesn’t cover everything. It doesn’t provide for the additional set of ECMAScript 5 Object enhancements which include an overhauled property/descriptor system that lets you do new things like use built-in getters/setters, mark properties as enumerable, writable, configurable and much more.

I bring this up only to point out that “traditional” prototypal inheritance and these new object features are not exclusive and can definitely be used in conjunction going forward. See this post on the Mozilla Developer Network for an example. And read this for more information on the new Object features of ECMAScript 5.

And finally I’d like to point out, a few folks out there are actually using Object.create to bypass the constructor altogether keyword and creating copies from an object without the need for instantiation (ie not using the “new” keyword). This is another totally valid option, but again, like the other existing class abstractions, and the upcoming native “class” implementation in ECMAScript 6, it masks the prototypal nature of javascript, which I highly recommend understanding fully before moving on to an alternate inheritance method.

Posted in Javascript | Leave a comment

Add Favicon To WordPress

Adding a favicon to your WordPress site is super easy!

Of course you’ll need a favicion file. If you don’t have one already use one of the many free online generators.

Once you have the favicon.ico file, upload it to your theme directory in the root (Same location as your style.css file).

Now simply add this one line in between your <head> and </head> tags.

	<link href="<?php echo get_stylesheet_directory_uri(); ?>/favicon.ico" rel="shortcut icon" />

That’s it! You’re done. You may need to clear your cache to see the results.

BTW the template which you the above code to will depend on your theme. For most themes you’ll find it in header.php. For example here’s my the beginning of my header template (header.php). Check out line 33…

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
	<meta charset="<?php bloginfo( 'charset' ); ?>" />
        <meta name="google-site-verification" content="cat_qv9C9PW70bRwrniM3agroxLV9wvjSwjz3YkXZcw" />
        <meta name="y_key" content="52d1e7d9581a44d4" />

	<title><?php
	// Returns the title based on the type of page being viewed
		if ( is_single() ) {
			single_post_title(); echo ' | '; bloginfo( 'name' );
		} elseif ( is_home() || is_front_page() ) {
			bloginfo( 'name' );
			if( get_bloginfo( 'description' ) )
				echo ' | ' ; bloginfo( 'description' );
			twentyten_the_page_number();
		} elseif ( is_page() ) {
			single_post_title( '' ); echo ' | '; bloginfo( 'name' );
		} elseif ( is_search() ) {
			printf( __( 'Search results for "%s"', 'twentyten' ), get_search_query() ); twentyten_the_page_number(); echo ' | '; bloginfo( 'name' );
		} elseif ( is_404() ) {
			_e( 'Not Found', 'twentyten' ); echo ' | '; bloginfo( 'name' );
		} else {
			wp_title( '' ); echo ' | '; bloginfo( 'name' ); twentyten_the_page_number();
		}
	?></title>
	<link rel="profile" href="http://gmpg.org/xfn/11" />
	<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" />
	<?php if ( is_singular() && get_option('thread_comments') ) wp_enqueue_script( 'comment-reply' ); ?>
	<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />

	/* FAVICON LINK */
	<link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri(); ?>/favicon.ico" />

	<?php wp_head(); ?>

</head>
Posted in Tips & Tricks | Leave a comment

Get Closest Square Root in Javascript – Job Interview Question

A recently hired colleague of mine (a Java developer) told me about one of his interview questions. In pseudo code he was asked to come up with a function to return the square root of a number and if the square root was not a whole number to return the next closest one that was.

Immediately I was thinking about how this would be done in javascript.

Of course the easiest way would just be…

function getClosestSqrt(number) {
	return Math.round(Math.sqrt(number));
}

Now granted it’s not much of an interview question if you’re allowed to use an existing square root function! So here’s my stab at coming up with an answer for that interview question in javascript, sans the Math.sqrt() method…

function getClosestSqrt(number) {

    // Let's only deal with numbers
    if (typeof number !== "number") { return undefined; }

    // Initialize some variables we'll use later
    var prevSqrt;
    var nextSqrt;

    // Set initial multiple to check against
    var multiple = 1;

    // Helper function to quickly return a number multiplied by itself
    function square(value) {
        return value * value;
    }

    // While multiple squared is less than or equal to our number execute this...
    while (square(multiple) <= number) {

        // If it's the same return our multiple because that's the square root!
        if (square(multiple) === number) {
            return multiple;
        }

        // Otherwise keep on trucking...
        multiple++;
    }

    /** Guess what? Our number doesn't have a whole integer as a square root **/

    // Store the next smallest and next largest square roots as variables
    prevSqrt = square(multiple - 1);
    nextSqrt = square(multiple);

    // Check which whole square root is closer and return that number
    return Math.abs(number - prevSqrt) <= Math.abs(number - nextSqrt) ? multiple - 1 : multiple;
}

And the output….


getClosestSqrt(4); // 2
Math.round(Math.sqrt(4)); // 2

getClosestSqrt(25); // 5
Math.round(Math.sqrt(25)); // 5

getClosestSqrt(29); // 5
Math.round(Math.sqrt(29)); // 5

getClosestSqrt(62); // 8
Math.round(Math.sqrt(62)); // 8

getClosestSqrt(100); // 10
Math.round(Math.sqrt(100)); // 10

getClosestSqrt(23940839483); // 154728
Math.round(Math.sqrt(23940839483)); // 154728

Essentially all my code is doing is performing a check against the square of every digit starting from 1 until the squared value is equal to or greater than our number. It returns the squared digit if there is a match otherwise it returns the closest whole square root.

See it action at jsFiddle

Good to know I’d have been able to answer the question! Can anyone think of a better way to do this?

Posted in Javascript | 1 Comment

MySQLi OOP connection example PHP


$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno())
{
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
}

$query = "SELECT * FROM users WHERE user_id='$userid'";

if ($result = $mysqli->query($query))
{
   while ($row = $result->fetch_assoc())
   {
       echo $row['name'] ."<br />";
   }
   $result->close();
}

$mysqli->close();
Posted in PHP | Leave a comment

Recursive Functions in PHP (Simple Examples)

A recursive function is a regular function which calls itself..


// Factorial example (ie 5 * 4 * 3 * 2 * 1)
function factorial($n) {

	if ($n == 1) return 1;
	return $n * factorial($n-1);

}

echo factorial(5); // Outputs 120

// Nested Array Summing Example
$example = array(1, 2, array(10,20,30), 4);

function sum_array($array) {

	$total = 0;
	foreach ($array as $element) {
		if(is_array($element)) {
			$total += sum_array($element);
		} else {
			$total += $element;
		}
	}
	return $total;

}
echo sum_array($example); // Outputs 67
Posted in PHP | 5 Comments

Switch Statement PHP (Simple Example)


$i = 1;
switch($i) {

 case 0:
 echo 'i equals 0';
 break;

 case 1:
 echo 'i equals 1';
 break;

 default:
 echo 'i equals the default value';

}

Posted in PHP | Leave a comment

Do-While Statement PHP (Simple Example)

$i = 0;
do { echo $i++; } while ($i <= 10);
Posted in PHP | Leave a comment

While Statement in PHP (Simple Example)

$i = 0;
while ($i <= 10) {

echo $i++;

}
Posted in PHP | Leave a comment

For Loop vs Foreach Loop in PHP (Simple Example)


// For Loop

for ($i = 1; $i <= 10; $i++) {

echo $i;

}


// Foreach Loop

$array = array("sample" => "value", "sample2" => "value2", "sample3" => "value3");

foreach ($array as $key => $val) {

echo $key  . ': ' .  $value . '<br />';

}

Posted in PHP | Leave a comment

WordPress get_the_content function no paragraph tags

Did you just use the WordPress get_the_content function and realize that all of the line breaks from the visual editor are not being returned as paragraph tags?

Solution: Apply the appropriate filters as outlined in the WordPress codex

<?php
$content = get_the_content();
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]&gt;', $content);

echo $content; ?>

Posted in Tips & Tricks, Wordpress | 4 Comments