I am creating a js library that handle item operations from collection object directly as follow. I want to allow to add dynamic user defined object function for each item and make these function available through collection object directly with index (please see example implementation).
var item = function (obj) {
this.foo = function () {
alert("foo" + this.name);
}
for (var i in obj) {
this[i] = obj[i]; //dynamic fields (overridable)
}
}
var collection = function (list) {
var self=this;
this.items = [];
if (list && list.length > 0) {
for (var i in list) {
var t = new item(list[i]); // create new item
for (var j in t) {
if (typeof (t[j]) === "function") {
this[j]=function(index,arg1,arg2,arg3){
self.items[index][j](arg1,arg2,arg3); //not working (unreliable)
console.log(j) //undefined
// problem is here j cannot be visible from function handler.
//I need to call dynamic j function within handler
}
}
this.items.push(t); //push each item into collection
}
}
}
}
var obj=new collection([
{
id:1,name:"apple",
bar:function(arg){
alert(arg+" "+this.name);
}
}
]);
obj.foo(0); //equivalent to obj.items[0].foo();
obj.bar(0,"parameter"); //equivalent to obj.items[0].bar("parameter");
As described in comments in above code snippet, I can't call item's function from collection function dynamically. How can I achieve this purpose. Please help me.
FUNCTION.namewill get the function name, is that what you want?