Javascript: A quick introduction to __proto__ and prototype

Javascript looks up a property on an object, student in our example. Javascript first looks at all the properties on student. If it doesn't find it, it looks at the properties on the __proto__ object, which is itself a property on student.

var school = {
  school_name: "Handsome boy modelling school"
}

var student = {
  name: "Nathaniel Merryweather"
}

student.name // outputs "Nathaniel Merryweather"
// student.school_name     will be undefined

student.__proto__ = school

console.log(student.name, student.school_name)
// outputs "Nathaniel Merryweather", "Handsome boy modelling school"

If we have lots of students, making a new object every time will become boring. We can use a function with new and this inside the function to make it easier.

var school = {
  school_name: "Handsome boy modelling school"
}

function Student(name) {
  this.name = name
}

var nathanial = new Student("Nathaniel Merryweather")
nathanial.__proto__ = school
console.log(nathanial.name, nathanial.school_name)

var chad = new Student("Chad Baker")
chad.__proto__ = school
console.log(chad.name, chad.school_name)

But we still have to manually add __proto__ to each object. We can make that easier by setting Student's prototype object to be our student object: it sets the object's __proto__ property when we make a new object.

var school = {
  school_name: "Handsome boy modelling school"
}

function Student(name) {
  this.name = name
}
Student.prototype = school

var nathanial = new Student("Nathaniel Merryweather")
console.log(nathanial.name, nathanial.school_name)

var chad = new Student("Chad Baker")
console.log(chad.name, chad.school_name)

Javascript is full of objects, Date as one example. All objects have properties. You can, at runtime, add new properties to all instances of any object. You do this by adding a new property to the prototype object.

var now = new Date()

now.custom_property // outputs undefined

Date.prototype.custom_property = "I am a custom property"

now.custom_property // outputs the above
javascript

Edit on github
comments powered by Disqus
Click me