JS ⟩ value ⟩ object ⟩ create ⟩ Object.create() ⟩ pure object
Object.create(null)
is an object without prototype.
this "pure" object will not inherit anything❗
does not have toString()
method.
won't work with +
operator.
can't call __proto__
(accessor).
const { log } = console;
// -----------------------------------
// ⭐ pure object without "prototype"
const obj = Object.create(null);
// -----------------------------------
// ⭐ can't get obj's [[Prototype]] using `__proto__` now.
// ⭐ `__proto__` is a getter/setter that resides in `Object.prototype`.
const proto = Object.getPrototypeOf(obj); // null
log(obj); // ⭐ [Object: null prototype]
// to silence the ⛔ TypeError, define `toString`:
// ⭐ regular property is "enumerable"
// obj.toString = () => `hi`;
// ⭐ use `Object.defineProperty` to define a non-enumerable property.
Object.defineProperty(obj, 'toString', {
value: () => `hi`,
})
// -------------------------------------------------------
// ⛔ TypeError: Cannot convert object to primitive value
// -------------------------------------------------------
log(`${obj}`); // ⭐ `obj` has no `toString()`❗
// -------------------------------------------------------
;
[
typeof obj, // 'object'
obj instanceof Object, // ⭐ false❗ (你說,JavaScript 是不是很亂搞 🙄)
Object.keys(obj), // [ 'toString' ] (if `toString` is enumerable)
// [ ] (if `toString` is non-enumerable)
proto === null, // true
obj.__proto__, // ⭐ undefined❗
].forEach(x => log(x));