Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing constructor in JavaScript

Tags:

javascript

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.

    <script type="text/javascript">

    function Me(){

      this.name = "Dejan";
    }

    function You(){

        this.name = "Ivan";
    }


    Me.prototype.constructor = You;
    somebody = new Me();


    alert(somebody.name); // **It gives Dejan, and I am expecting Ivan**

    </script>
like image 295
Dexy_Wolf Avatar asked Jun 30 '11 01:06

Dexy_Wolf


2 Answers

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.

like image 160
RobG Avatar answered Oct 05 '22 11:10

RobG


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); 
like image 44
jzilla Avatar answered Oct 05 '22 11:10

jzilla