Here is a possible explanation:
(Note: the explanation below is only for experimentation and conceptual understanding, since __proto__ should be avoided in production code)
As you know, there is a connection between the object (in this case, a1) and the prototype of the constructor function (in this case, A) from which the object is created. This link is called __proto__ or dunder proto. Therefore, in this case it can be seen as a1.__proto__ .
Now what happens when you say A.prototype = {}; , at this time, the a1 object was already constructed, and it points to A.prototype through this link.
Since Javascript is a garbage collector, just setting A.prototype to {} does not clear the old protoytpe object directly, which means the older object is still delayed. Therefore, when you say console.log(a1.howCool()); , howCool is in a lingering object.
So, if you change your line3 as follows:
// line3
console.log(a1.__proto__); a1.__proto__ = {}; console.log(a1.howCool());
You can see the old prototype object and howCool () inside it in the console window in the console.log(a1.__proto__); line console.log(a1.__proto__); However, if you set a1.__proto__ = {}; , then console.log(a1.howCool()); cannot find the object, and the Cool () method will not be found (since now it is set to an empty object).
So, just setting A.prototype to {} does not achieve the same effect as a.__proto__ = {}.
Therefore, the result that you see.
Hope this helps.
Pankaj shukla
source share