Let's say that I'm making a JS library that has some functions for DOM manipulation. I have a few functions that are added to elements, for example myElement.empty();
. I would like the same functionality for NodeList
s (the objects returned from, for example, querySelectorAll
). To dynamically add the functions, I have done the below (and please note that the below does work):
var funcs=["text","html","attr","remove","empty","css"];
var n=funcs.length;
while(~--n){
var f=function(){
var i,l=this.length;
for(i=0;i<l;i++){
this[i][ funcs[arguments.callee.n] ].apply(this[i], arguments);
}
return this;
};
f.n=n;
NodeList.prototype[funcs[n]]=f;
}
This works, but I have heard that arguments.callee
doesn't work in "strict" mode.
Someone said to give the function a name, but I can't, although I tried:
var funcs=["text","html","attr","remove","empty","css"];
var n=funcs.length;
while(~--n){
this[funcs[n]]=function(){
var i,l=this.length;
for(i=0;i<l;i++){
this[i][ funcs[name] ].apply(this[i], arguments);
// In the above it has 'name' which references the function name
}
return this;
};
NodeList.prototype[funcs[n]]=this[funcs[n]];
}
That didn't work. I was able to do it using I decided not to use eval
.eval
, although it worked (by putting n
into the string and making the function out of that). I figured that arguments.callee
is probably better than eval
, if I had to use one of them.
How can I make my function work without using anything that is suggested against (such as arguments.callee
and eval
)?
Edit for more details:
Let's say I define an empty
function (and once again for the purpose of the question let's assume that modifying the prototype is OK):
Element.prototype.empty=function(){
while(this.childNodes[0])
this.childNodes[0].remove();
};
This works for one element. What if the user wants to do something similar to:
document.querySelectorAll("button .myclass").empty();
So I want to make a script that dynamically creates functions for NodeLists
that call the corresponding functions for each element, for example:
NodeList.prototype.empty=function(){
var i,l=this.length;
for(i=0;i<l;i++)
this[i].empty();
return this;
};
If I want to do the above I will need to create many functions that do very similar things. So I want to write some code that dynamically creates functions for NodeList
. As you probably read above, I did it with arguments.callee
(and eval
), but I want to use something that is standard and considered OK to use.
How would I do this?
If you need any more information then please ask in the comments, and I will try to respond as soon as possible.