Javascript object lost constructor when the prototype was changed

后端 未结 3 2054
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 01:28

In below code

var A = function() {};
var a = new A();
var b = new A();

A.prototype = {};

var c = new A();
console.log(a.constructor === b.constructor);
con         


        
3条回答
  •  臣服心动
    2021-01-14 01:55

    When using function as an object constructor, its prototype.constructor is automatically created with function's property. So initially after setting up the A function you will have a constructor in A's prototype:

    A.prototype.constructor
    

    So when you assign A.prototype ={}, you lost that original constructor in A.prototype.

    You may fix it with adding this after A.prototype ={} line

    A.prototype.constructor = A;
    

    Both console should log true

提交回复
热议问题