@Muggy Ate
How do I iterate through from track0 to trackn? I know I can do something like song["track" + n] but that's what I'm doing right now and my goal is to move my functions into the song JSON object so I can iterate faster... Or is there no performance gain to be had at all if I just moved my functions into the object?
There are a lot of ways to achieve this. I will just propose one way.
You can have only one function that performs what you need, a only function that can run in the context of the object you need. Also by injecting the context, you can create references to that function inside other objects, e.g:
function iterator (criteria) {
var obj = this,
prop;
for (prop in obj) {
//TODO: Add what you need to do in each iteration
if (obj[prop] == criteria) { return prop; }
}
}
//mockups
var song1 = { "track0": "data0", "track1": "data1" },
song2 = { "track0": "data0", "track1": "data1" };
//iterates over song1 object,
//for this case, we look for the property that has the value "data0"
var something = iterator.call(song1, 'data0');
//something = "track0"
Another advantage is that you can also create objects using prototypal inheritance.
If you want to extend your objects by adding the methods, you can do it, as we saw in the previous example, we used this
inside the iterator
function, and that give us the advantage working with different objects
//extends obj by attaching new methods
//and binding the execution context of the methods
function addMethods(obj) {
obj.iterator = iterator.bind(obj);
}
addMethods(song1);
addMethods(song2);
//we use the "iterator" method extended inside song2
something = song2.iterator('data1');
//something = "track1"
`var myObj = { key: 'value', prop: 'value' }`
And this is a JSON `var json = '{ "key": "value", "prop": "value" }'`
(I enclosed the string in a single quote, to avoid escape the standard double quotes)_ – jherax Oct 25 '15 at 20:13