JavaScript Prototyping
Simple example with a constructor function
Create a Constructor Function
// 1. Create a function -> 'constructor'
function Person() {
this.name = "John";
this.age = 25;
}
// 2. Create an object with this constructor function
let person1 = new Person(); // {name: "John", age: 25}
Add Properties to the Prototype
// 3. Add properties to the prototype of the Person function
// These properties will be shared by all objects created with Person
Person.prototype.age = 30; // This value will be "hidden" by the object's value
Person.prototype.city = "Paris"; // New property available to all
// IMPORTANT: Never do Person.prototype = {age: 30, city: "Paris"}
// because this would break the prototype chain!
Prototype Chain
// 4. How JavaScript searches for properties:
// Prototype chain: person1 ---> Person.prototype ---> Object.prototype ---> null
console.log("=== Property Tests ===");
console.log(person1.name); // "John"
// JavaScript finds 'name' directly on person1
console.log(person1.age); // 25
// JavaScript finds 'age' on person1 (value 25)
// It ignores the value 30 from the prototype (this is "shadowing")
console.log(person1.city); // "Paris"
// JavaScript does not find 'city' on person1
// It looks in Person.prototype and finds "Paris"
console.log(person1.country); // undefined
// JavaScript does not find 'country' anywhere:
// 1. Not on person1
// 2. Not on Person.prototype
// 3. Not on Object.prototype
// 4. Reaches null = end of search, returns undefined
Practical Examples
Native Array Methods
let numbers = [1, 2, 3];
numbers.push(4); // Where does this push() method come from?
// It comes from Array.prototype.push!
Add a Method to All Arrays
// Add a method to all arrays (use sparingly! It can break things and pollute the namespace!)
Array.prototype.last = function() {
return this[this.length - 1];
};
let fruits = ['apple', 'banana'];
console.log(fruits.last()); // "banana"
Example with jQuery
// This also helps understand things like jQuery that you will / have already seen!
// jQuery does this internally:
function jQuery(selector) {
// selection logic...
}
jQuery.prototype.hide = function() {
// hides the element
};
$('.button').hide(); // uses the prototype!