DEV Community

yorrran
yorrran

Posted on

prototype and constructor

First, let's take a look of some concepts in javascript.
Object - non-primitive data type that holds multiple values in terms of properties and methods.

function Person(){
  this.name = 'parent';
  this.age = 1;
  sayHi: function() {
      console.log('sayHi')
      }
}
Enter fullscreen mode Exit fullscreen mode
console.log(Person)
Enter fullscreen mode Exit fullscreen mode

Image description

console.log(Person.prototype)
Enter fullscreen mode Exit fullscreen mode

Image description

You can use prototype property to access constructor function and proto property.

prototype - every function and object has prototype property by default
constructor - constructor function is same as other language which is used for creating and instantiating object. There are two conventions:

  • name is first letter capitalized
  • use with new operator as default

The relationship between prototype and constructor is:
Image description

When creating new instance

const p1 = new Person();
Enter fullscreen mode Exit fullscreen mode
console.log(p1)
Enter fullscreen mode Exit fullscreen mode

Image description
The relationship between Object Person and instance is:
Image description

By understanding difference between prototype and proto, and constructor, let's deep into some of the type checking methods that we use and how prototype helps on it.

  • constructor

From above relationship diagram, you will notice that constructor actually refers back to object on the prototype chain that prototype is the property. It can be used to find the constructor function when creating instance.

const arr = [];
Enter fullscreen mode Exit fullscreen mode
console.log(arr.constructor)
Enter fullscreen mode Exit fullscreen mode

Image description

  • instanceof
console.log(arr instanceof Array) // true
console.log(arr instanceof Object) // true
Enter fullscreen mode Exit fullscreen mode

Image description
From chaining you can see instanceof uses prototype chaining to go back all the way to find presence of contructor.prototype, therefore it is instance of both Array and Object.

Hope this article can help you understand prototype in javascript.

Top comments (0)