DEV Community

Sleepless Yogi
Sleepless Yogi

Posted on

JavaScript as Prototype-based language

  • JavaScript does not contain "classes" that defines a blueprint for the object, such as is found in C++ or Java
  • JavaScript uses functions as "classes"
  • Everything is an object in JavaScript
  • In JavaScript, objects define their own structure
  • This structure can be inherited by other objects at runtime

What is a prototype?

  • It is a link to another object
  • In JavaScript, objects are chained together by prototype chain
Joe -> Person -> Object -> null

Enter fullscreen mode Exit fullscreen mode
  • JavaScript objects inherit properties and methods from a prototype

Example of Prototype

  • Prototype property allows you to add properties and methods to any object dynamically

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

Animal.prototype.age = 10

Enter fullscreen mode Exit fullscreen mode
  • When object Cat is inherited from object Animal
    • Then Animal is the prototype object or the constructor of the Cat

var cat = new Animal('cat')
console.log(cat) // constructor: "Animal"
console.log(cat.name) // cat
console.log(cat.age) // 10

Enter fullscreen mode Exit fullscreen mode

I love jotting down my thoughts on my blog Ninja Academy. And, if you are looking to level up your Web Development chops, do check out my Ultimate Web Development Bootcamp.

Top comments (0)