Prototype
This post is an intro to Js - Prototype Object.
Whenever we create a function in javascript, javascript engine creates two object for us.
The two objects that are created when Js engine process the function are ,
Function object which inturns the function itself ,
Prototype Objects.
What is prototype
The prototype in Js is used primarily for inheritance, you add methods and properties on a function’s prototype property to make those methods and properties available to instances of that function.
function foo() {
console.log("Hello!!");
}
// foo.prototype
Whenever Js engine creates the prototype object it also creates a property in function called prototype. With the help of this prototype property in function, we can access the prototype object created for that function.
For example we have seen foo function which has a property called prototype pointing to prototype object. To make use of the prototype object we create an object using the new keyword.
var myObj = new foo();
// myObj
When we create a object myObj Js engine creates an object for us which in default have an object called "proto". Which in turns points to the initial prototype object created by the function.
Working With Proto
Now that we know there is proto object created by Js engine whenever we create a object to see how it function,lets create a property "say" in the "myObj" object with value "Hi from myObj itself".
function foo(){}
var myObj = new foo();
myObj.say = "Hi from myObj itself";
When we access "myObj.say" we know that it will return the value "Hi from myObj itself".We create another object to the proto object with the same property but with different value "Hi from proto object"
function foo(){}
var myObj = new foo();
myObj.__proto__.say = "Hi from proto object";
Accessing the "myObj.proto.say" will return "Hi from proto object".
function foo(){}
var myObj = new foo();
myObj.say = "Hi from myObj itself";
// Hi from myObj itself
myObj.__proto__.say = "Hi from proto object";
// Hi from proto object
delete myObj.say;
// true
myObj.say
// Hi from proto object
But when we delete the "myObj.say" and access the same, the Js engine go look at the "proto" object to see, if there is any propert "say". Which will find the property "myObj.proto.say", with the value "Hi from proto object" and this will be returned while accessing "myObj.say".
Now that we know whenever we create an object, Js engine creates an another object for us called prototype. We can access the prototype using ".prototype" from the function. But when we create an object using new keyword, Js creates "proto", which points to the prototype object.
Whenever we look for an property in an object, the Js engine will return it- if it finds it in the object itself. If there is no such property, Js engine will look upto the prototype object.
Top comments (1)
Awesome article! Thank you.