__proto__
You can edit the prototype in order to pass data to every instance of the object.
Why create properties and methods in the prototype when you can just as easily create them in the object constructor itself?
this
to bind to only that particular instance, you have no relation with the object constructor. You are binding to the particular instance. Whereas in Prototype, you bind to the constructor. You’re not pointing to methods in the instance you created, you’re pointing to methods in constructor. Any change in constructor gets reflected in all instances because they’re all pointing to the same prototype. 1// Object constructor function
2function Person(firstName, lastName, age) {
3 this.firstName = firstName
4 this.lastName = lastName
5 this.age = age
6 // Object method
7 // Changes to an object method only effects object instances created AFTER the change
8 this.greet = function () {
9 console.info(`Hello ${this.firstName} ${this.lastName}`)
10 }
11}
12
13// Prototype
14// Adding a method to prototype
15// Changes to a prototype method instantly updates all objects using that prototype
16Person.prototype.details = function () {
17 // it's not the prototype of Person, it's the prototype of any object created from Person
18 console.info(`${this.firstName} ${this.lastName} is ${this.age} year(s) old`)
19}
20
21// Creating a new instance of the Person object
22let john = new Person('John', 'Denver', 28)
23console.info(john) // Person { firstName: 'John', lastName: 'Denver', age: 28, greet: [Function] }
24
25// Test Prototype method and Object method
26console.info(john.details()) // John Denver is 28 year(s) old
27console.info(john.greet()) // Hello John Denver
28
29// Changes to an Object Method vs. Changes to a Prototype Method
30Person.greet = function () {
31 console.info(`Hello there ${this.firstName} ${this.lastname}, you amazing fellow!`)
32}
33
34Person.prototype.details = function () {
35 console.info(`${this.firstName} ${this.lastName} is ${this.age} year(s) old and he is amazing!`)
36}
37
38// Let's test the changes
39console.info(john.details()) // John Denver is 28 year(s) old and he is amazing! >> Prototype method updated the existing object
40console.info(john.greet()) // Hello John Denver >> Object method missing our updates
41
42// Check out the prototype of an object
43console.info(john.__proto__) // Person { details: [Function] }