Dexy_Wolf
Dexy_Wolf

Reputation: 999

Changing constructor in 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>

Upvotes: 6

Views: 11141

Answers (4)

personal_cloud
personal_cloud

Reputation: 4494

As RobG's answer explains, the browser is broken. Identifying the problem is a great first step. However, while "The browser is broken so fix your program" can solve the problem, "The browser is broken so fix the browser" is more logical. Here's one possible polyfill for new.

function NEW(clas, ...args)
{
  let res = Object.setPrototypeOf({}, clas.prototype);
  res.constructor.apply(res, args);
  return res;
}

This fixes the browser so you don't need to change your prototype. Only a minor change is required, to change new to NEW:

Me.prototype.constructor = You;
somebody = NEW(Me);
alert(somebody.name);

And this produces the desired result ("Ivan").

Upvotes: 0

RobG
RobG

Reputation: 147403

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.

Upvotes: 14

jzilla
jzilla

Reputation: 1703

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); 

Upvotes: 5

DrStrangeLove
DrStrangeLove

Reputation: 11557

try:

Me.prototype = new You();

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


    alert(somebody.name); 

Upvotes: 0

Related Questions