Changing constructor in JavaScript

前端 未结 3 732
醉酒成梦
醉酒成梦 2020-12-11 19:41

I am trying for a while to switch constructor for a object and I am failing. Continuing code will show example of what I need. Thanks.

    

        
相关标签:
3条回答
  • 2020-12-11 19:45

    The Me.prototype.constructor property is just a public property of Me.prototype, it is not used in any way in the construction of new objects or resolution of property names.

    The only vague interest it has is that intially it references the function that its prototype "belongs" to and that instances of Me inherit it. Because it is a public property that can easily be assigned a new value or shadowed, it is not particularly reliable unless you have tight control over it and the code using it.

    0 讨论(0)
  • 2020-12-11 19:54

    You can't change the constructors of an object, you can however change the 'type' of the object the constructor returns, with (as in your example)

    Me.prototype = new You();
    

    which would cause new Me()'s to inherit from the object You. However this.name in the Me() function will overshadow the one inherited from you so do something like this:

    function Me(){
        this.name =  this.name || "Dejan";
    }
    function You(){
        this.name = this.name || "Ivan";
    }
    Me.prototype = new You();
    somebody = new Me();
    alert(somebody.name); 
    
    0 讨论(0)
  • 2020-12-11 20:08

    try:

    Me.prototype = new You();
    
    Me.prototype.constructor = You;
        somebody = new Me();
    
    
        alert(somebody.name); 
    
    0 讨论(0)
提交回复
热议问题