1

I'm looking to prototype a method onto records I receive back from a database.

I found this answer already, but it requires you to instantiate a new object for every object you already have. This seems like a lot of work, but may be the only way.

Is there a way to prototype a method onto all objects in a JSON string that does not involve instantiating a new object for every record?

Community
  • 1
  • 1
Nick Brown
  • 1,167
  • 1
  • 21
  • 38

2 Answers2

2

As I said in the comments, you can use a simple reviver function within the JSON parsing, as long as you keep the keys in mind. See this jsFiddle: http://jsfiddle.net/38Ytc/3/ This is an example, let's suppose you got the JSON string somewhere (in the example, from a textbox), and you need to add certain functions to the objects returned by this data. We then call parse with an reviver function as the second argument, that will be called for each key within the data structure. For our minimal example, it would convert all non-array objects except the top level object (key "") to a DataRow object, which has the methods get, set and save.

var inputEl = $("#exampleInput");
var outputEl = $("#exampleOutput");

function DataRow(contents) {
    this.object = contents;
}
DataRow.prototype.get = function(key) {return key?this.object[key].object:this.object;};
DataRow.prototype.set = function(key, val) {if (key) {this.object[key] = val;} else {this.object = val;};};
DataRow.prototype.save = function() {/*Save to DB or whatever*/};

inputEl.change(function() {
    var resultObject = JSON.parse( inputEl.val(),function(key, val) {
        if (key === "" || typeof val === Array) { //See MDN for why this is necessary
            return val;
        } else {
            return new DataRow(val);
        }
    });
    console.log(resultObject.entries.object[0].get("title"));
    outputEl.val(JSON.stringify(resultObject));
});

After this processing, you could simply use resultObject.entries.object[0].get("title") to get a object's title, if it exists.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

0

You wouldn't even need to call bind() in this situation unless you want to access properties of the object via the 'this' keyword. If you do not need access to the object you could simply do this:

var records = [{'val':1},{'val':2}];

records.forEach(function(record){
    record.someMethod = function(){
      console.log('Some action');
    }
});

records[1].someMethod();
records[0].someMethod();
Josh Taylor
  • 532
  • 2
  • 8
  • 1
    This isn't really prototyping, though, it's just looping and appending a method. Unfortunately that's what I'm trying to avoid by utilizing prototyping. – Nick Brown Dec 12 '13 at 21:18