Inheritance of Properties

JS
S
JavaScript

Basic example of properties inheritance using functions as object construct. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

1function uniqueClass() {}
2
3uniqueClass.prototype.stdProp = 1;
4
5
6Object.defineProperty(uniqueClass.prototype, "pvt", {
7  get() {
8    return this.val;
9  },
10  set(x) {
11    this.val = x;
12  }
13});
14
15let value;
16Object.defineProperty(uniqueClass.prototype, "shared", {
17  get() {
18    return value;
19  },
20  set(x) {
21    value = x;
22  }
23});
24
25
26const unique1 = new uniqueClass();
27const unique2 = new uniqueClass();
28
29// Set only on unique1
30unique1.val = 2;
31unique1.shared = 4;
32unique1.stdProp = 3;
33
34unique1.random = 7;
35
36unique1.pvt = 8767;
37console.log(unique1.pvt); // 8767
38console.log(unique2.pvt); //  undefined
39
40console.log(unique1); // val:2, stdProp:3
41console.log(unique2); // {}
42
43console.log(unique2.stdProp); // 1
44console.log(unique1.stdProp); // 3
45console.log(uniqueClass.prototype.stdProp); // 1
46
47console.log(unique1.shared); // 4
48console.log(unique2.shared); // 4
49
50console.log(unique1.random); // 7
51console.log(unique2.random); // undefined
52

Created on 6/13/2018