-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObject.create.js
More file actions
48 lines (35 loc) · 1.52 KB
/
Copy pathObject.create.js
File metadata and controls
48 lines (35 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const obj1 = { "abc": "xyz" };
const newObj = Object.create(obj1);
console.log(newObj); // {}
console.log(newObj.__proto__); // { “abc”: “xyz” }
// prototypal inheritance
const obj2 = {
greet: function() {
console.log("hey bro");
}
}
const obj3 = Object.create(obj2);
console.log("obj3", obj3); // obj3 itself is empty
obj3.greet(); // but it has inherited all properties from obj2, those properties exists in its prototype chain
obj2.hello = function() {
console.log("hello word");
}
obj3.hello(); // as the reference of the object is stored in the prototype chain of the created object (using Object.create()) so if a new property/key is added in the original object, prototype of the created object can access that too
// // used to create pure object (with no prototype properties, even not the default ones)
// const pureObj = Object.create(null);
// console.log("pureObj proto", pureObj.__proto__)
// console.log(pureObj.toString); // undefined
// // used to define custom properties with strict access rules
// const carPrototype = {
// drive() { console.log("Vroom!"); }
// };
// const myCar = Object.create(carPrototype, {
// make: {
// value: "Tesla",
// writable: false, // Cannot be changed (read-only)
// enumerable: true, // Shows up in for...in loops
// configurable: true // Can be deleted or modified later
// }
// });
// myCar.make = "BMW"; // Ignored in strict mode / fails silently otherwise
// console.log(myCar.make); // Output: "Tesla"