Skip to content

Instantly share code, notes, and snippets.

@patitonar
Created November 22, 2018 00:15
Show Gist options
  • Save patitonar/37d102f86a0b3ee929d5ec8e9759f438 to your computer and use it in GitHub Desktop.
Save patitonar/37d102f86a0b3ee929d5ec8e9759f438 to your computer and use it in GitHub Desktop.
An example of how javascript prototype works
// Create a Person function
function Person(first, last) {
this.firstName = first;
this.lastName = last;
}
// Function Person and Person.prototype are created
typeof Person // "function"
typeof Person.prototype // "object"
const martin = new Person("Martin", "Larsson")
// The prototype of martin is Person.prototype
Object.getPrototypeOf(martin) === Person.prototype; // true
// The prototype of Person.prototype is Object.prototype
Object.getPrototypeOf(Person.prototype) === Object.prototype; // true
// Object.prototype does not have a prototype
Object.getPrototypeOf(Object.prototype) === null; // true
// The traversal algorithm consults the object’s prototype when it cannot find the desired property on the object.
// If it finds the property on the prototype, the traversal stops.
// Otherwise, it will consult the prototype of the prototype, and so on, until it finds the property or it reaches the end of the prototype chain.
// In this example greet() function is not defined on martin's object
// neither it is on Person.prototype
// nor Object.prototype
martin.greet() // Uncaught TypeError: martin.greet is not a function
// Let's add greet() on Object.prototype
Object.prototype.greet = function() {
console.log(`Hi!`)
}
// greet() found on Object.prototype
martin.greet() // Hi!
// Let's add greet() on Person.prototype
Person.prototype.greet = function() {
console.log(`Hi ${this.firstName}, ${this.lastName}!`)
}
// greet() found on Person.prototype
martin.greet() // Hi Martin, Larsson!
// Let's add greet() on martin's object
martin.greet = function() {
console.log(`Hi from martin's object!`)
}
// greet() found on martin's object
martin.greet() // Hi from martin's object!
// If we create a new person, greet() will be found on Person.prototype
const soren = new Person("Soren", "Bjerg")
soren.greet() // Hi Soren, Bjerg!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment