javascript add prototype method to all functions?

Viewed 28874

Is there a way to add a method to all javascript functions without using the prototype library?

something along the lines of :

Function.prototype.methodName = function(){ 


  return dowhateverto(this) 

 };

this is what i tried so far but it didnt work. Perhaps it is a bad idea also if so could you please tell me why?

if so can I add it to a set of functions i choose

something like :

MyFunctions.prototype.methodName = function(){ 


  return dowhateverto(this) 

 };

where MyFunctions is an array of function names

thank you

4 Answers

Sure. Functions are objects:

var foo = function() {};

Function.prototype.bar = function() {
  alert("bar");
};

foo.bar();

Will alert "bar"

function one(){
    alert(1);
}
function two(){
    alert(2);
}

var myFunctionNames = ["one", "two"];

for(var i=0; i<myFunctionNames.length; i++) {
    // reference the window object, 
    // since the functions 'one' and 'two are in global scope
    Function.prototype[myFunctionNames[i]] = window[myFunctionNames[i]];
}


function foo(){}

foo.two(); // will alert 2

Changing JS built-in objects can give you some surprises.
If you add external libraries or changing the version of one of them, you are never sure that they won't overwrite your extension.

Related