Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to turn a JSON array of object back in to the Object type sharing prototypes?

If you have an array of product objects created from JSON, how would you add a prototype method to the product objects so that they all point to the same method? How would you train JavaScript to recognize all product objects in an array are instances of the same class without recreating them?

If I pull down a JSON array of Products for example, and want each product in the array to have a prototype method, how would I add the single prototype method to each copy of Product?

I first thought to have a Product constructor that takes product JSON data as a parameter and returns a new Product with prototypes, etc. which would replace the data send from the server. I would think this would be impractical because you are recreating the objects. We just want to add functions common to all objects.

Is it possible to $.extend an object's prototype properties to the JSON object so that each JSON object would refer to exactly the same functions (not a copy of)?

For example:

var Products = [];
Products[0] = {};
Products[0].ID = 7;
Products[0].prototype.GetID = function() { return this.ID; };
Products[1].ID = 8;
Products[1].prototype = Products[0].prototype;  // ??

I know that looks bad, but what if you JQuery $.extend the methods to each Product object prototype: create an object loaded with prototypes then $.extend that object over the existing Product objects? How would you code that? What are the better possibilities?

like image 741
Zachary Scott Avatar asked Jun 08 '11 19:06

Zachary Scott


1 Answers

For one, you're not modifying the Products[0].prototype, you're modifying Object.prototype, which will put that function on the prototype of all objects, as well as making it enumerable in every for loop that touches an Object.

Also, that isn't the proper way to modify a prototype, and ({}).prototype.something will throw a TypeError as .prototype isn't defined. You want to set it with ({}).__proto__.something.

If you want it to be a certain instance you need to create that instance, otherwise it will be an instance of Object.

You probably want something like:

var Product = function(ID) {
    if (!this instanceof Product)
        return new Product(ID);

    this.ID = ID;

    return this;
};

Product.prototype.GetID = function() { 
    return this.ID;
};

Then, fill the array by calling new Product(7) or whatever the ID is.

like image 147
Robert Avatar answered Nov 07 '22 17:11

Robert