Mostafa Mahmoud
Mostafa Mahmoud

Reputation: 568

function.prototype.method

I would like to ask about the code below

Function.prototype.method = function (name, func) {
   this.prototype[name] = func;
   return this;
};

Does that mean that "Function" and any new function will inherit functions created by method?

To make it more clear

Function.method('test', function () {return 1;});

is test now available to be called as a method on Function or any other function or not?

Upvotes: 1

Views: 1186

Answers (2)

Ry-
Ry-

Reputation: 224913

No, this inside a function refers to the object on which it was called. In this case, that should be a function, and more specifically, a constructor function. It should be used like:

function SomeObject() {}

SomeObject.method('doSomething', function() {
    alert('Something!');
});

new SomeObject().doSomething(); // Something!

Upvotes: 2

Trent Earl
Trent Earl

Reputation: 3607

JavaScript is a protypical language. When a function is called on an object and not found a search begins up the prototype chain. It will search all objects in the prototype chain until the prototype chain ends at Object, the parent of all objects.

All functions inherit from Function either directly or indirectly, meaning all functions will have your specified "method", even functions that have already been created.


Function.prototype.printSup = function () { console.log('sup'); }
Math.max.printSup();
String.pringSup();
'asdf'.substr.printSup()

Upvotes: 0

Related Questions