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')
}
}
console.log(Person)
console.log(Person.prototype)
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:
When creating new instance
const p1 = new Person();
console.log(p1)
The relationship between Object Person and instance is:
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 = [];
console.log(arr.constructor)
- instanceof
console.log(arr instanceof Array) // true
console.log(arr instanceof Object) // true
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)