Skip to content

Commit a58834a

Browse files
feat: add object prototypes
1 parent da292ea commit a58834a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
INFO: Object Prototypes
3+
JavaScript is prototype-based, meaning every object in JavaScript has a hidden [[prototype]] (commonly accessed via .prototype or __proto__).
4+
*/
5+
6+
/*
7+
INFO: What is prototype ?
8+
A prototype is just another object that your object inherits properties and methods from.
9+
*/
10+
const user = {
11+
name: "Rafay",
12+
greet() {
13+
console.log(`Hello, ${this.name}`);
14+
}
15+
};
16+
17+
const admin = {
18+
role: "admin",
19+
};
20+
21+
admin.__proto__ = user;
22+
23+
console.log(admin.name); // "Rafay"
24+
admin.greet(); // Hello, Rafay
25+
26+
/*
27+
INFO: Object.getPrototypeOf() and Object.setPrototypeOf()
28+
you can also get/set protypes programmatically:
29+
*/
30+
Object.getPrototypeOf(admin); // user
31+
Object.setPrototypeOf(admin, {}); // change prototype
32+
33+
/*
34+
INFO: Object.prototype
35+
Every object eventually links to Object.prototype, unless you create it with Object.create(null).
36+
*/
37+
38+
/*
39+
INFO: Prototype Chain
40+
When you access a property:
41+
1. Js looks at the object itself.
42+
2. If not found, it looks in its prototype.
43+
3. Then the prototype's prototype... and so on, until it hits null.
44+
This is called Prototype Chain.
45+
*/
46+
47+

0 commit comments

Comments
 (0)