简体   繁体   中英

using prototype functions for an array of object literals

I am using PHP, MySQL, and javascript. I use php to connect to my database to select appointments. I then echo them in a script tag as arrays of object literals (JSON objects):

appointment[$apptid] = {"time":"8:00", "date":"2012-02-10", "description":"testAppt"};
...

I chose to do it this way over writing an appointment "class" in case I add or remove appointment fields, however I can't figure out for the life of me how to create functions that will apply to this array of objects. Is there anyway to declare these as appointment objects and then write prototype functions without losing the properties?

I'm not 100% sure that I understand what you're after, but if I understand then maybe this is what you want:

First of all, in javascript you better use arrays in a different way than in php, so do something like:

var appointments = [];
appointments.push({"time":"8:00", "date":"2012-02-10", "description":"testAppt"});

Now, once you the array you can do something like:

function doSomething() {
    alert(this.time);
}

for (var i = 0; i < appointments.length; i++) {
    appointments[i].doSomething = doSomething;
}

Check out JSON.parse : http://www.json.org/js.html

Using this, you can parse your JSON strings into appointment objects that contain your variables as defined in the JSON string, with no prototyped functions.

Then, if you want to get really fancy, you can use the "reviver" parameter to pass in a function in which you could define the functions for each appointment object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM