Domanda

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.

È stato utile?

Soluzione

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; 
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top