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>
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With