Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript add prototype method to all functions?

Tags:

javascript

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

like image 283
salmane Avatar asked Jan 24 '10 11:01

salmane


People also ask

Do functions have prototype JavaScript?

A Function object's prototype property is used when the function is used as a constructor with the new operator. It will become the new object's prototype. Note: Not all Function objects have the prototype property — see description.

What is the difference between __ proto __ and prototype?

The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.

Do all objects have prototype in JavaScript?

Each and every JavaScript function will have a prototype property which is of the object type. You can define your own properties under prototype . When you will use the function as a constructor function, all the instances of it will inherit properties from the prototype object.

What is __ proto __ in JS?

__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).


1 Answers

Sure. Functions are objects:

var foo = function() {};

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

foo.bar();

Will alert "bar"

like image 197
troelskn Avatar answered Oct 29 '22 20:10

troelskn