๐ [[HomeObject]]
๐ง under construction
Last updated
๐ง under construction
Last updated
JS โฉ types โฉ object โฉ method โฉ HomeObject
๐ง
const { log } = console;
let animal = {
sayHi() { log(`I'm a ๐ถ`) } // [[HomeObject]] === animal
};
let rabbit = {
__proto__: animal,
sayHi() { super.sayHi() } // [[HomeObject]] === rabbit
};
let plant = {
sayHi() { log("I'm a โ๏ธ") } // [[HomeObject]] === plant
};
let tree = {
__proto__: plant,
// (non-method syntax for objectsโ)
// ----------------------------------------------------------------
// โญ `rabbit.sayHi` method remembers its [[HomeObject]]โ
// โญ `tree.sayHi` is NOT a methodโ
// (just a "reference" to another method)
sayHi: rabbit.sayHi // [[HomeObject]] === rabbit
// ----------------------------------------------------------------
};
tree.sayHi();
// super.sayHi() // โญ in `rabbit.sayHi` method
//
// super === [[HomeObject]].[[Prototype]]
// === rabbit.[[Prototype]]
// === animal
//
// animal.sayHi() // "I'm a ๐ถ"
โญ๏ธ ้ๅธธ้่ฆ๏ผ
only methods have [[HomeObject]]
.
[[HomeObject]]
canโt be changed.
super can only be used within methods.
super === [[HomeObject]]
.
[[Prototype]]
โญ๏ธ
for objects, methods must be specified๏ผ
as method()
(method syntax)
not as nonMethod: function()
(non-method syntax)
const { log } = console;
// -------------------------------------------------------------
// โญ๏ธ only methods have [[HomeObject]].
// โญ๏ธ `super` can only be used in a method (with [[HomeObject]])
// โญ๏ธ super === [[HomeObject]].[[Prototype]]
// -------------------------------------------------------------
// โ regular function
// --------------------
function f1(){ super.method() }
// ^^^^^ // โ๏ธ SyntaxError: 'super' unexpected here.
// โ arrow function (not in a method)
// ------------------------------------
let f2 = () => super.method();
// ^^^^^ // โ๏ธ SyntaxError: 'super' unexpected here.
const a = {
// โ object property (function as property value)
// ------------------------------------------------
nonMethod: function(){ super.method() }
// ^^^^^ // โ๏ธ SyntaxError: 'super' unexpected here.
}
const b = {
// โ
object method:
// ------------------
// โข [[HomeObject]] === b
// โข super === [[HomeObject]].[[Prototype]]
// === b.[[Prototype]]
// === Object.prototype
method(){ log(`${super.constructor.name}`) }
}
b.method(); // Object
a method's HomeObject is only used when calling super.
super === [[HomeObject]]
.
[[Prototype]]
โญ๏ธ
mixin inheritance is possible through [[HomeObject]].