3

is it possible to extend the function-prototype of "myfunction" - without a manipulation of Function.prototype - in the same way it is possible to extend the object-prototype (myfunction.prototype.method = function(){})?

Kind regards

readme_txt
  • 71
  • 4
  • 1
    "Is it possible"? Try it and see :). – Heretic Monkey Oct 07 '18 at 18:05
  • @HereticMonkey :-D – readme_txt Oct 07 '18 at 18:05
  • extending a builtin prototype of a javascript object will lead to prototype pollution – 0.sh Oct 07 '18 at 18:58
  • Thanks for your answers. But it is possible to create a constructor-function "myfunction" and to add methods to its prototype-object by myfunction.prototype.funnyfunction = function(){}. So my question is: is it possible to extend the prototype-function in a similar way - without the manipulation of Function.prototype? – readme_txt Oct 07 '18 at 19:04
  • Are you referring to [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static)? – Patrick Roberts Oct 07 '18 at 19:48
  • You can [extend `Function`](https://stackoverflow.com/q/36871299/1048572) to create your own kind of functions, but no, the prototype of normal `function() {}`s is `Function.prototype` and to add methods to all of them you need to manipulate `Function.prototype`. – Bergi Oct 07 '18 at 19:48

2 Answers2

1

Yes, we can extend function prototype. Every javascript function inherits from built in Javascript Function object, and therefore are type of Function object. W3schools example:

function Person(first, last, age, eyecolor) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
    return this.firstName + " " + this.lastName;
};

W3schools link MDN Link Function

Note: Never modify default prototype of any javascript object.

binf
  • 76
  • 1
  • 3
  • Thank you for your answer. I thought that Person.prototype.name = function(){} extends the object.prototype of Person and not the function.prototype? – readme_txt Oct 07 '18 at 18:59
  • You are correct about that. Consider Person as a type of Function object, it inherited all the default prototype from Function object and we can also add to its prototype properties and methods. The built in Function.prototype cannot be modified. – binf Oct 08 '18 at 08:33
0

Regarding native functionality, JavaScript has prototype into the depths of its core. Although not clear, you could use extension onto Native Prototypes, including, among others, the Function objects.

I would suggest being careful of doing so though, as this might lead to unexpected behaviors and side effects - as on every change of "default", native functionality, as this can be a bad idea.

Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54