0

I'm struggling to set the instance of a protype. I've got something like this:

function Course() {
    // Some stuff
}

Course.prototype.MyMethod = function() {
    // Do stuff
}

Now if I create a New Course(), all works fine, however, I'm getting the Courses from JSON. So what I wanted to do is:

data.forEach(function(courseFromJSON) {
    courseFromJSON.prototype = Course.prototype;
    courseFromJSON.prototype = new Course(); // Doesn't work either
});

But my courses never get the method MyMethod set to them. Neither is setting courseFromJSON.prototype to new Course(). I've been going through Douglas Crockford's video's, but can't seem to get it right. What am I doing wrong?

Thanks.

4
  • stackoverflow.com/questions/7015693/… Commented Oct 14, 2013 at 8:49
  • Thanks @Vandesh, I had read that, the code uses the .prototype = something, which is what I tried. But it also states, that it only reflects on the child instances. Question remains: how do I get my prototype methods working on stuff incoming from JSON? Commented Oct 14, 2013 at 8:54
  • ok, so courseFromJSON.__proto__ = Course.prototype seems to work Commented Oct 14, 2013 at 8:58
  • and why it works, is mentioned too :) Commented Oct 14, 2013 at 9:00

1 Answer 1

1

Your code wasn't working because you can't change the prototype of an already created object, or at least not via the prototype property.

Two alternatives exist:

  1. Use the internal __proto__ property, but this is not recommended because it is a non-standard property.

  2. Use the setPrototypeOf(Object, prototype) function, this is recommended and will be standardized in ES6.

Or even better, use the code snippet taken from the documentation link on setPrototypeOf():

Object.setPrototypeOf = Object.setPrototypeOf || function (obj, proto) {
    obj.__proto__ = proto;
    return obj; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, especially for the recommendation on which option to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.