Reputation: 329
I have a bunch of JSON string returned from an ajax call in a specific format and when starting to convert them all into my own Javascript object, I start to wonder if there is any easier way since we're talking Javascript here.
I'll have var manyOfThem = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
And I'd like to easily associate each of these objects with my functions so that I can do things like:
myClass.prototype.doSomething = function() {
// do something to this.name
};
$.each(manyOfThem, function(index, item) {
item.doSomething();
});
I guess my concern is, I would not want to (because its repetitive) do this:
var myClass = function(item) {
this.name = item.name;
// do the same for the rest of item's potentially 20 properties
};
var oneOfThem = new myClass(manyOfThem[0]); // I think this is redundant....
oneOfThem.doSomething();
Anyhow, if there is also (security?) reasons why I'd just have to suck it up and do them all manually please share as well, thanks!
Upvotes: 5
Views: 142
Reputation: 53531
You mean, something like (see jsfiddle) :
var MyClass = function() {};
MyClass.prototype = {
doSomething: function() {
alert(this.name);
}
};
Then
var manyObj = $.map(manyOfThem, function(obj) {
return $.extend( new MyClass(), obj );
});
So you can call :
manyObj[0].doSomething(); // alert("a")
However, this approach will not preserve a direct copy with the manyOfThem
object. (In the example above, changing manyOfThem[0].name = "foo";
will not affect manyObj[0]
and a call to manyObj[0].doSomething();
will still alert "a"
. To preserve a direct reference to your object, do this :
var manyObj = $.map(manyOfThem, function(obj) {
function F() {};
F.constructor = MyClass;
F.prototype = obj;
$.extend(F.prototype, new MyClass());
return new F();
});
manyObj[0].doSomething(); // alert("a")
manyOfThem[0].name = "foo"; // modify the referenced object
manyObj[0].doSomething(); // alert("foo") ..also modifies the behaviour of the instance
Upvotes: 3
Reputation: 388316
One solution without using a class is
var manyOfThem = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
function doSomething(){
console.log(this.name)
}
$.each(manyOfThem, function(index, item) {
doSomething.call(item);
});
Demo: Fiddle
If you want to create an instance of type MyClas
then
var manyOfThem = [ { name: 'a' }, { name: 'b' }, { name: 'c' } ];
function MyClass(item){
$.extend(this, item);
}
MyClass.prototype.doSomething = function(){
console.log(this.name)
}
$.each(manyOfThem, function(index, item) {
var obj = new MyClass(item);
obj.doSomething()
});
Demo: Fiddle
Upvotes: 2
Reputation: 745
You can do
var myClass = function(item){
for( i in item){
if (item.hasOwnProperty(i)){
this[i] = item[i];
}
}
};
This should reduce the repetitive assignments in myClass
constructor.
Upvotes: 0