Javascript and jQuery

Useful Javascript/jQuery snippets as they Must Be Built.

Limit The Number of Checkboxes 'checked' with jQuery

Quick code snippet. Assume you have:

<p>Best Cheese? Please select the three:</p>
<div>
   <label><input type="checkbox" name="Cheddar" value="1" class="limitThree">Cheddar</label>
   <label><input type="checkbox" name="Cheshire" value="1" class="limitThree">Cheshire</label>
   <label><input type="checkbox" name="Creamy Lancashire" value="1" class="limitThree">Creamy Lancashire</label>
   <label><input type="checkbox" name="Cheshire" value="1" class="limitThree">Double Gloucester</label>
   <label><input type="checkbox" name="Red Leicester" value="1" class="limitThree">Red Leicester</label>
   <label><input type="checkbox" name="Stilton " value="1" class="limitThree">Stilton</label>
   <label><input type="checkbox" name="Wensleydale" value="1" class="limitThree">Wensleydale</label>
</div>

Then you could use the following jQuery:

$('.limitThree').on('change', function(){
	var noChecked = 0;
	$.each($('.limitThree'), function(){
		if($(this).is(':checked')){
			noChecked++;	
		}
	});
	if(noChecked >= 3){
		$.each($('.limitThree'), function(){
			if($(this).not(':checked').length == 1){
				$(this).attr('disabled','disabled');	
			}
		});
	}else{
		$('.limitThree').removeAttr('disabled');	
	};
});

Recursive Javascript Functions

Just posted a codepen if anyone looking at Recursive Javascript functions.  The scenario here could I am sure be tackled other ways but I wanted to do it with a recursive function.

Given an array of random numbers, the function getNewNumber will finish off the array by populating it with the remaining number between 1 and 10, done in a random order.

var bunchOfNumbers = [1,4,5];
var getNewNumber = function(){
    var tempNo = Math.ceil(Math.random()*10);
    tempNo ? 11 : tempNo--;
    for (var i = 0; i < bunchOfNumbers.length; i++) {
        if (bunchOfNumbers[i] == tempNo) {
          document.getElementById('error').innerHTML += "Number in use:"+tempNo+"<br>";
           return getNewNumber();
        }
     }
    bunchOfNumbers.push(tempNo);
    if(bunchOfNumbers.length < 10){
      return getNewNumber();
    }else{
      return true;
    }
}
getNewNumber();
console.dir(bunchOfNumbers);
document.getElementById('msg').innerHTML = bunchOfNumbers.toString();

I needed a version of this for ensuring an object was not placed at the same coordinates as other objects in an array of coordinates.

View Codepen

Post Script

Some more thoughts on this. Here is an example that checks to see if a PIN number is unique. I am using Firebase to store the PINs.

var getNewNumber = function(){
  var newPin;
  newPin = Math.round(Math.random()*100000)+10000;
  newPin = String(newPin);
  newPin = newPin.substring(1, 5);
  db.ref('cpUsers/').orderByChild("pin").equalTo(newPin).on("value", function(snapshot){
	if(snapshot.val() === null){
             db.ref('cpUsers/').push({pin: newPin}).then(function(snapshot){
	     return snapshot.key;
	     },function(error){console.info(error)});
	}else{
	    return getNewNumber;
	}
   });
}

Validating Radio Buttons Using Javascript (jQuery)

In online surveys you may want users to have to answer a radio button style question. You can set a default value with checked as follows:

<input id="female" name="gender" type="radio" value="F" checked>
<label for="female">Female</label>
<input id="male" name="gender" type="radio" value="M">
<label for="male">Male</label>

However, you have to make a decision what the default with be and for lazy form fillers you might end up with incorrect data.

In HTML5 radio buttons we can use the required attribute ie

<input id="female" name="gender" type="radio" value="F" required>
<label for="female">Female</label>
<input id="male" name="gender" type="radio" value="M">
<label for="male">Male</label>

This is great but comes with the inevitable HTML5 caveats that it just can't be relied on across all browsers.

So for true radio button validation we need a Javascript solution .... and as ever I've used jQuery here to help.

The HTML/CSS Set Up

Firstly lets add some HTML to provide error messages.

<input type="radio" name="gender" value="F" id="female">
<label for="female">Female</label>
<input id="male" name="gender" type="radio" value="M" />
<label for="male">Male</label>
<span class="error"> *Required</span>

The <span> needs to be hidden initially so in the CSS we'll add:

.error{
display:none;
}

The Javascript

The jQuery is called when the form is submitted. For those in a hurry here is the code:

$('form').submit(function() {
	 $('.error').hide();
	  var radioList = $('input:radio');
	  var radioNameList = new Array();
	  var radioUniqueNameList = new Array();
	  var notCompleted = 0;
	  for(var i=0; i< radioList.length; i++){
		  radioNameList.push(radioList[i].name);
	  }
	  radioUniqueNameList = jQuery.unique( radioNameList );
	  for(var i=0; i< radioUniqueNameList.length; i++){
		  if(typeof($('input:radio[name='+radioUniqueNameList[i]+']:checked').val()) === "undefined"){
			  $('input:radio[name='+radioUniqueNameList[i]+']').parent().find('.error').show();
			  notCompleted++;
		  }
		}
	 if(notCompleted > 0){
		 return false;
	 }else{
		 return true;
	 }
});

View CodePen

How it works?

The Javascript firstly switches off all the .error messages just in case one is already live.

$('.error').hide();

Next a list of the radio buttons is created:

var radioList = $('input:radio');

This will give me a list of all the radio buttons. What we really want are the radio groups. So in order to get this two arrays are created to store all the names and then refine that list of the unique names.

Looping around the radioNameList array we populate radioNameList with all the names. Then jQuery.unique allows use to refine this to an unique list.

Once we have this list of unique radio group names we can loop these checking to see there is a checked value in each group. If a radio group does not have a checked value undefined is returned. When this happens by navigating the DOM we can switch on the related .error message.

The notCompleted variable is used to keep count of things. So if the number of non-completions is greater than zero the form isn't submitted.

This may seem over engineered but it is designed so that multiple radio button groups can be validated. Here is a fuller example:

View Demo

This can probably be refactored so comments welcomed to refine the idea.

Lazy form fillers - lazy line painters.

Adding Form Fields Dynamically with Knockout.js

A couple of years ago I did a post entitled Adding Form Fields Dynamically with jQuery.  In this post I am going to re-visit the same problem but this time use Knockout.js to create the dynamic form fields.

View The Demo

Introducing Knockout.js

Knockout.js is a Model-View-View-Model Javascript library. What it excels at is 'binding' data such as Javascript objects, arrays and JSON to your output HTML. To use Knockout.js take a trip to knockoutjs.com to view their excellent tutorials and documentation. To use it you need to either download the Knockout.js file or you can use a distributed version of the file by adding:

<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js">
</script>

Data Binding

Knockout.js works by 'binding' your data model to your HTML output. The hook it uses for this are HTML's custom attributes. Primarily this is done by declaring a data-bind on a HTML element and then adding some knockout.js logic to it.

<div data-bind="someCommand">

Note: HTML attributes are part of the HTML5 specification but you can safely use in both newer HTML5 browsers as well as older ones.

In our example we are going to set up the HTML form as follows:

<form method="post">
<div data-bind="foreach: myFieldList">
  <p>
  <label data-bind="text: label"></label>
  <input data-bind="attr: { name: fname}">
  <span class="removeVar" data-bind="click: removeField">Remove Variable</span>
   </p>
</div>

<p>
<span id="addVar" data-bind="click: addField">Add Variable</span>
</p>

<p class="alignRight">
<input type="submit" value="Check">
</p>

</form>

Notice the use of the data-bind custom attribute to bind various Knockout.js commands to the HTML elements

The Javascript itself consists of:

function fieldModel(){
        var self = this;
	var noTracker = 3;
	self.myFieldList = ko.observableArray([{label : "Variable 1", fname : "var1"},{label : "Variable 2", fname : "var2"},{label : "Variable 3", fname : "var3"}]);

	self.removeField = function(dynamicField){
	    self.myFieldList.remove(dynamicField);
	}

	self.addField = function() {
	    noTracker++;
	    self.myFieldList.push({label : "Variable "+ noTracker, fname : "var"+ noTracker});
    	}
}
ko.applyBindings(fieldModel);

Primarily this is involved in creating a data model fieldModel with initial properties as well as a couple of methods removeField and addField. This is fundamentally 'vanilla' Javascript apart from ko.observableArray which is Knockout's extended version of an array that makes it easier to manipulate, and the ko.applyBindings(fieldModel); that 'binds' our data model to the HTML above.

Strictly Javascript

There comes a time with a large Javascript project where having the code behave more like a 'usual' programming language becomes useful.  This is where 'strict mode' comes in.

Javascript is very forgiving.  Take the following:

myMsg = "Hiya";

No problem.  Yet programming from other languages will throw their arms in horror - The Variable has not been declared! We have a variable without declaring it with the var keyword.  If you want to enforce the use of the var keyword, to for example keep track of scope, then you can add the following:

'use strict'
myMsg = "Hiya";

The above will throw an error.  However if we amend the code to:

'use strict'
var myMsg;
myMsg = "Hiya";

This will be valid as the variable has been properly declared with var.

JS Fiddle

Scope

You can limit the 'strictness' to a function by declaring 'use strict' inside a function so that the strict rules only apply to that function ie:

function showMsg(){
    // only strict in the function
    'use strict'
    var myMsg1 = "local stuff"; 
    return myMsg1;
}

JS Fiddle

Beyond the declaration of variables strict mode will also add restrictions such as:

  • Preventing writing to read only properties
  • Stopping the extension of non-extensible objects
  • Preventing the duplication of object literal properties
  • Preventing the use of 'future' reserved words such as a 'public', 'static' and 'private'

For more information see MSN on Strict Mode

Storing Values with Javascript's localStorage

As part of the range of new HTML5 Javascript goodies localStorage allows developers to store data client side for later reuse. Sounds familiar? Yep, just like cookies, but without the size limitations as you can store Megabytes of data using localStorage.

Setting Values

To set a localStorage value you use the method setItem().

localStorage.setItem(name,value);

So to set a value of 'Creamy Lancashire' to an item named 'cheese' we would use:

localStorage.setItem('cheese','Creamy Lancashire');

Getting Values Back

To get values back from localStorage we use the getItem() with the syntax:

localStorage.getItem(name);

So the cheesy example would be:

var perfectWithBiscuits = localStorage.setItem('cheese');

Optional extra info on getters and setters (Tell me more)

Getters and Setters

An alternative to the methods of setItem() and getItem() is to use the 'name' as a getter/setter. An alternative way to get and set values would therefore be:

// to set
localStorage.cheese = 'Creamy Lancashire');
// to get
var perfectWithBiscuits = localStorage.cheese;

Both should be supported but as ever check with your target browsers. One difference is the messages returned when the values are not set. The setItem() method returns null whilst the getter returns undefined.

View Demo

An Example with a Colour Picker

In this demo localStorage is used to store the background colour you pick, such that when you return to the page after closing the browser it remembers your choice.

//set value
localStorage.myBgColour=newColour;
//get value
bgColour = localStorage.myBgColour

The rather neat Javascript Colour picker here comes courtesy of Spectrum.

View Demo

Dividing Dynamic Content equally into Columns

The CSS float property is often used to create columns. Waiting in the wings are some newer techniques such as the CSS column-count property which will make adding columns much easier.

For example given a HTML snippet of :

<ul>
<ul>
	<li>ALFA ROMEO</li>
	<li>AUDI</li>
	<li>AUSTIN</li>
	<li>BMW</li>
        .. etc etc
        <li>TOYOTA</li>
	<li>TRIUMPH</li>
	<li>VAUXHALL</li>
	<li>VOLKSWAGEN</li>
	<li>VOLVO</li>
</ul>

We can use the following CSS to put the list into 5 nice columns.

	column-count:5;
	column-gap:40px;
	column-rule-width:1px;
	column-rule-style:outset;
	column-rule-color:#ccc;

View Demo

This is particularly useful when your content (in this case a list) is dynamic and you don't know how many items you're doing to have and therefore how many items to place in each list.

A Javascript Fallback

However, as caniuse kindly tell us we can't use this technique with IE9 or earlier.

Here is a solution I came up with. Assuming we want 5 columns set up the HTML as follows:

<div id="colsContainer">
 	<div><ul></ul></div>
	<div><ul></ul></div>
	<div><ul></ul></div>
	<div><ul></ul></div>
	<div><ul></ul></div>
</div>

The dynamic data I am going to use here is a Javascript array.

var myArray = new Array('ALFA ROMEO','AUDI','AUSTIN','BMW', .... 'VOLKSWAGEN','VOLVO');

The following Javascript counts the number of values in the array and then works out how to distribute them evenly across, in this case, five columns. The maths trick here is the use of the modulus (%) to divide the items by the number of columns but distribute the remainder to the left-hand columns.

 var noCols = 5;
 var displayData = "";
 var startVal = 0;
 var endVal = 0;
 for(var i=0;i<noCols;i++){
     if(i < myData.length%noCols){
         endVal =+ (endVal+Math.floor(myData.length/noCols)+1);
     }else{
         endVal =+ (endVal+Math.floor(myData.length/noCols));
     }
     displayData = ""
     for(var j=startVal;j<endVal;j++){
         displayData += '<li><a href="">';
         displayData += myData[j];
         displayData += '</a></li>';
     }
     startVal = endVal;
     $('#modelList div ul').eq(i).html(displayData);
 }

View Demo

Ternary, Tilde ~ and Modulus - Javascript Tricks

Ternary

The ternary operator makes for a shorthand if ... else

condition : if true do this ? else to this

For example the following if ... else:

var myWeight = 120;
var msg = "";
if(myWeight > 80){
    msg = "big";
}else{
    msg = "small";
}

... can be done with the ternary operator with:

var myWeight = 120;
var msg = (myWeight > 80) ? "big" : "small";

JSFIDDLE Demo

Waltzing (m)tilde ~

The little used tilde character ~ is a bitwise operator that works right down on the bits - that is the zeros and ones.

The tilde reverses the order of the bits. The logic is ~N is -(N+1).

var myNum = 10;
myNewNum = ~myNum;
// myNewNum = -11

JSFIDDLE Demo

Running a variable through another tidle ie ~~ will switch the bits back to their original order.

JSFIDDLE Demo

But if you run a boolean false or true through a double tilde ~~ it has the effect of changing the value into an integer 0 or 1.

var myWeight = 120;
document.getElementById('display').innerHTML = ~~(myWeight > 80);

JSFIDDLE Demo

Math with Modulus %

Modulus % will return the remainder of a division, and subsequently zero if the number is divisible by an integer.

12 % 5 = 2
10 % 5 = 0
104 % 100 = 4

Any number below the number to be divided will always return a value equal to itself. As the number will go into the number to be divided zero times and then what is left is the remainder. So:

1 % 10 = 1
2 % 10 = 2
7 % 10 = 7
8 % 10 = 8
9 % 10 = 9

... but

10 % 10 = 0

This is a useful way to keep track of whether an incrementing value has hit the top target value.

for(var i=0; i<15; i++){
    if((i % 10) === 0){
        document.getElementById('display').innerHTML = i;
    }
}

JSFIDDLE Demo

How do you function?

Javascript functions can be written in a number of different ways.

Function declarations

Firstly we have the 'classic' named function:

function eatLead(){
  // do something
}
// and the call
eatLead();

This technique is known as a 'function declaration'.

JSFIDDLE Demo

Function Expressions

Then we have the anonymous function:

document.getElementById('myButton').addEventListener('click', function(){
  // do something
});

The above function has no name and is associated with an event. This technique is a type of 'function expression'.

JSFIDDLE Demo

We can also create a function expression by assigning it to a variable:

var eatLead = function() {
    // do something
}

The function still needs to be invoked with:

eatLead();

JSFIDDLE Demo

Functions defined via Functions Expressions can be named or anonymous. A named variant would be:

var fire = function eatLead() {
    // do something
}

JSFIDDLE Demo

Note that eatLead() is undefined outside the scope of the eatLead() function. This won't work:

var fire = function eatLead() {
    // do something
}
document.getElementById('display').innerHTML = eatLead();
//eatLead() is undefined outside the scope of eatLead()

JSFIDDLE Demo

Functions can also be self invoking with the addition of some parenthesis.

//self invoking function expression
(function() {
    // do something
})();

Notice how this self invoking function is placed in parenthesis as function expressions cannot start with the keyword function. It is the second pair of brackets at the end that call the function.

JSFIDDLE Demo

If we wanted to send some parameters to the self-invoking function then we can do that to:

//self invoking function expression
(function(cheese) {
    alert(cheese);
})('cheddar');

JSFIDDLE Demo

We can have named self-invoking functions. You might need one of these if the function's logic requires it to call itself, for example:

var cheeseCounter = 0;
(function eatCheese(cheese) {
    document.getElementById('display').innerHTML += cheese;
    cheeseCounter++;
    if(cheeseCounter < 10){
        eatCheese(' more, ');
    }
})('cheddar');

JSFIDDLE Demo

Using jQuery with a self-invoking function

A common trick with jQuery is to use the self-invoking function style and feed to it jQuery as a parameter.

(function($){
    // do something
})(jQuery)

The benefit of this is that the $ sign is internal to the self-invoked function so it leaves the potential to use other libraries ... if you really felt the need to.

Javascript Prototypes

Classes, Properties, Methods and Ships

Javascript is an object oriented (OO) programming language. Many object oriented programming languages, such as Java and ActionScript, are class based.

Titanic_plan

A 'class' acts as a blueprint for objects or instances created from the blueprint. We may, for example, have a class 'Ship' that defines the basic characteristics of a Ship - its crew, displacement and speed for example. These would be 'properties' of a Ship created from that class. The blueprint/class would also outline what the object it creates can do - its methods - so our Ship can moveForward(), tootHorn(), sink(). In short properties are adjectives/descriptive, whilst methods are doing words/verbs.

A class is abstract, it doesn't exist until you instantiate an object - build a ship, from the blueprint. So at the shipyard the blueprint in the company office is the class, but as a ship built from the blueprint rolls down the slipway it is very much an object. In many languages the process of instantiating an object is done with the new keyword ie:

var titanic = new Ship();

When we create something from the class, we have physically created something and this is an object. An object can have properties that describe it and methods that prescribe what it can do. So our ship has properties of crew, displacement and speed, and methods of moveForward(), tootHorn() and sink().

The joy of classes is that we can have many objects based on it. For example did you know that titanic had a sister ship called 'Olympic'.

var olympic = new Ship();

... and here they both are:

Olympic_and_Titanic

Note: You may be interested to know that shipbuilding and many other industries use the concept of 'classes'. For example Titanic and Olympic were both 'Olympic' class liners and indeed there was a third class member Britannic.

Conventions

You'll notice some conventions here. Class names are capitalized ie Ship, whilst property names are lowercase. Methods are often verbNoun - what is known as camelCasing where we start with a lowercase word then have a capitalized second word. Methods will normally have parenthesis - brackets () - as methods often takes values such as tootHorn('loudly') or moveForward(500).

Inheritance

A key benefit of object oriented programming languages is that of inheritance. We already have our Ship class but there might be more subtle classifications of Ship such as Liner, WarShip, Ferry and OilTanker. These will all have the same 'base' characteristics of the Ship class, so there is no need to indicate that each will have a crew, tootable horn and might sink. These properties and methods can be 'inherited' from Ship.

But Javascript is class-less

Unlike the accommodation on the Titantic - Javascript is 'class-less'. Javascript does not have a class keyword like for example ActionScript. Javascript is a prototype based programming language. Instead of 'classes', in Javascript objects can inherit properties and methods from each other by the cloning of an existing object known as a prototype. Whenever you create an object in Javascript such as an array or string - these are objects based on a prototype. You can also create your own objects and have them act as prototypes and even extend the prototype of built-in objects. Let's take a look.

Prototypes and Objects

In Javascript we can create Objects using a function like so:

function Ship(c, d, s){
 this.crew = c;
 this.displacement = d;
 this.speed = s;  
}
var titanic = new Ship(892, 52310, 24);
document.getElementById('display').innerHTML = titanic;

JSFIDDLE Demo

In the above example the output is the rather cryptic object object. This is because to see anything meaningful we need to loop through the object properties.

Using a for ... in loop we can make more sense of the values:

function Ship(c, d, s){
 this.crew = c;
 this.displacement = d;
 this.speed = s;   
}
var titanic = new Ship(892, 52310, 24);
for (var prop in titanic) {
     if(titanic.hasOwnProperty(prop)){
        document.getElementById('display').innerHTML += prop;
        document.getElementById('display').innerHTML += ": ";
        document.getElementById('display').innerHTML += titanic[prop];
        document.getElementById('display').innerHTML += "<br>";
     }
}

JSFIDDLE Demo

Tip: Notice the use of the capitalized function name to indicate that this function is used to create an object. This kind of function is known as a constructor.

Inheritance

ark_royal

Now if we extend this example by creating a new 'classification' of Ship ie 'Warship'.

function Ship(c, d, s, b){
 this.crew = c;
 this.displacement = d;
 this.speed = s; 
 this.built = b; 
}
function WarShip(c, d, s, g){
 this.crew = c;
 this.displacement = d;
 this.speed = s;   
 this.guns = g;
}
WarShip.prototype = new Ship();
var arcRoyal = new WarShip(685, 22000, 30, 5);

for (var prop in arcRoyal) {
        document.getElementById('display').innerHTML += prop;
        document.getElementById('display').innerHTML += ": ";
        document.getElementById('display').innerHTML += arcRoyal[prop];
        document.getElementById('display').innerHTML += "<br>";
}

We now have a Ship and WarShip constructor functions that can be used to create objects. We also create a new WarShip using the line:

WarShip.prototype = new Ship();

This makes Ship the base or prototype of the WarShip object. We then create a new object from WarShip with:

var arcRoyal = new WarShip(685, 22000, 30, 5);

Notice however, that when we loop through the properties with a for ... in we have an undefined value for the property built.

JSFIDDLE Demo

This is because of something called the prototype chain. The for ... in is looking at all the properties of the object included those that it is based upon. By 'based upon' what we really mean is the Prototype of the object. Therefore as Ship has a property of built, and as it is the Prototype of WarShip, the Ship property gets picked up and happens to be undefined.

To avoid this we use hasOwnProperty that ensures only properties that belong to the current object are returned. Therefore in the for ... in the code is changed to:

for (var prop in arcRoyal) {
     if(arcRoyal.hasOwnProperty(prop)){
        document.getElementById('display').innerHTML += prop;
        document.getElementById('display').innerHTML += ": ";
        document.getElementById('display').innerHTML += arcRoyal[prop];
        document.getElementById('display').innerHTML += "<br>";
     }
}

JSFIDDLE Demo

Extending an object with prototype

The prototype property is used in the example below to extend the Ship object with a new method of setSpeed(). This new method is then available to all objects that build on Ship in this case both titanic and olympic.

function Ship(c, d, s, b){
 this.crew = c;
 this.displacement = d;
 this.speed = s; 
 this.built = b; 
}
Ship.prototype.setSpeed = function (spd) {
    this.speed = spd;
};
var titanic = new Ship(892, 52310, 24, 1911);
titanic.setSpeed(48);
var olympic = new Ship(900, 52607, 24, 1910);
olympic.setSpeed(65);
for (var prop in titanic) {
     if(titanic.hasOwnProperty(prop)){
        document.getElementById('display').innerHTML += prop;
        document.getElementById('display').innerHTML += ": ";
        document.getElementById('display').innerHTML += titanic[prop];
        document.getElementById('display').innerHTML += "<br>";
     }
}
for (var prop in olympic) {
     if(olympic.hasOwnProperty(prop)){
        document.getElementById('display').innerHTML += prop;
        document.getElementById('display').innerHTML += ": ";
        document.getElementById('display').innerHTML += olympic[prop];
        document.getElementById('display').innerHTML += "<br>";
    }
}

JSFIDDLE Demo

We could also add a new property to the prototype with:

Ship.prototype.builder = "Harland and Wolff, Belfast";

As both ships were built at Harland and Wolff in Belfast we would like to add this to the prototype. If we add this to our example:

function Ship(c, d, s, b){
 this.crew = c;
 this.displacement = d;
 this.speed = s; 
 this.built = b; 
}
Ship.prototype.setSpeed = function (spd) {
    this.speed = spd;
};
var titanic = new Ship(892, 52310, 24, 1911);
titanic.setSpeed(48);
var olympic = new Ship(900, 52607, 24, 1910);
olympic.setSpeed(65);
Ship.prototype.builder = "Harland and Wolff, Belfast";
for (var prop in titanic) {
     if(titanic.hasOwnProperty(prop)){
        document.getElementById('display').innerHTML += prop;
        document.getElementById('display').innerHTML += ": ";
        document.getElementById('display').innerHTML += titanic[prop];
        document.getElementById('display').innerHTML += "<br>";
     }
}
for (var prop in olympic) {
    if(olympic.hasOwnProperty(prop)){
        document.getElementById('display').innerHTML += prop;
        document.getElementById('display').innerHTML += ": ";
        document.getElementById('display').innerHTML += olympic[prop];
        document.getElementById('display').innerHTML += "<br>";
    }
}

JSFIDDLE Demo

We might expect to see the builder property listed but it isn't. This is because of hasOwnProperty is preventing both of our ships from moving up the prototype chain to the Ship class. All we see is the properties of titanic and olympic directly. So if we remove hasOwnProperty then we will see our new property.

function Ship(c, d, s, b){
 this.crew = c;
 this.displacement = d;
 this.speed = s; 
 this.built = b; 
}
Ship.prototype.setSpeed = function (spd) {
    this.speed = spd;
};
var titanic = new Ship(892, 52310, 24, 1911);
titanic.setSpeed(48);
var olympic = new Ship(900, 52607, 24, 1910);
olympic.setSpeed(65);
Ship.prototype.builder = "Harland and Wolff, Belfast";
for (var prop in titanic) {
        document.getElementById('display').innerHTML += prop;
        document.getElementById('display').innerHTML += ": ";
        document.getElementById('display').innerHTML += titanic[prop];
        document.getElementById('display').innerHTML += "<br>";
}
for (var prop in olympic) {
        document.getElementById('display').innerHTML += prop;
        document.getElementById('display').innerHTML += ": ";
        document.getElementById('display').innerHTML += olympic[prop];
        document.getElementById('display').innerHTML += "<br>";
}

JSFIDDLE Demo

Extending Built-in Functions

By referencing the prototype of a built-in function we can extend their functionality. So keeping the nautical theme we can add a new method to String as follows:

String.prototype.pirateSpeak = function(){
	return this + ", me hearties.";	
};
var testString = "Hello";
testString = testString.pirateSpeak();

The above create a new method for String objects called pirateSpeak(). This can be referenced whenever we have a string in the same way as built-in String methods like replace(). The this keyword inside the method refers to the current objects value.

JSFIDDLE Demo

The 'non-standard' __proto__

The strangely typed __proto__ is an internal property of an object, pointing to its prototype. As such it can be used to point at the prototype via the instance. Take the following example:

var testString = "Hello";
var moreStrings = "Goodbye";
moreStrings.__proto__.pirateSpeak = function(){
	return this + ", me hearties.";	
};
// same as //
//String.prototype.pirateSpeak = function(){
//	return this + ", me hearties.";	
//};
testString = testString.pirateSpeak();
moreStrings = moreStrings.pirateSpeak();

JSFIDDLE Demo

Life does get complicated with Prototypes you might want to dive deeper here: