The following code snippet shows Function
and Object
become each other’s instance.
// below code snippet shows Function is an instance of Object
Function instanceof Object; // true
Object.prototype.isPrototypeOf.call(Function.prototype, Object); // true
Function.prototype.isPrototypeOf(Object); // true
// below code snippet shows Object is an instance of Function
Object instanceof Function; // true
Object.prototype.isPrototypeOf.call(Object.prototype, Function); // true
Object.prototype.isPrototypeOf(Function); // true
// below code snippet means both Function.__proto__ and Object.__proto__ reference the same object in memory
Object.is(Function.__proto__, Object.__proto__); // true
Object.getPrototypeOf(Function) === Object.getPrototypeOf(Object); // true
Function.constructor.prototype === Object.constructor.prototype; // true
Function.__proto__ === Object.__proto__; // true
And also, Function
MDN web page and Object
MDN web page, shows Function
and Object
inherit each other?
screenshot of Function
MDN web page
screenshot of Object
MDN web page
In my opinion, an instance is initialized/generated by a class, but a class should not initialized/generated by an instance.
I know that OOP in js is prototype-based OOP, and it would be a little different from traditional OOP(like python OOP), I still can’t understand Why did Function
and Object
become each other’s instance? is this kinda wired in logic?
And another question: how to implement that AClass
and BClass
become each other’s instance?
Is the following example correct?
// example for making `MyClass1` and `MyClass2` become each other's instance
class MyClass1 { constructor() {} }
class MyClass2 { constructor() {} }
Object.setPrototypeOf(MyClass1, MyClass2.prototype);
Object.setPrototypeOf(MyClass2, MyClass1.prototype);
// below code snippet shows MyClass1 is an instance of MyClass2
MyClass1 instanceof MyClass2; // true
Object.prototype.isPrototypeOf.call(MyClass2.prototype, MyClass1); // true
MyClass2.prototype.isPrototypeOf(MyClass1); // true
// below code snippet shows MyClass2 is an instance of MyClass1
MyClass2 instanceof MyClass1; // true
Object.prototype.isPrototypeOf.call(MyClass1.prototype, MyClass2); // true
MyClass1.prototype.isPrototypeOf(MyClass2); // true