💠[[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]].