1

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?

asked Dec 24, 2012 at 3:38
0

2 Answers 2

2

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!
answered Dec 24, 2012 at 3:41
Sign up to request clarification or add additional context in comments.

2 Comments

Try to define the function using the code I have attached above. After defining a function this way, I haven't been able to find it on Function's prototype or any other function. It was only available in objects created by the function and I don't know why ?!
@MostafaMahmoud: Ah, sorry, I misread this as Function. It’s supposed to be used on constructors. See edit.
0

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()
answered Dec 24, 2012 at 3:40

3 Comments

The parent of all objects! Except for DOM nodes in Internet Explorer 8 and earlier, you know, because.
Try to define the function using the code I have attached above. After defining a function this way, I haven't been able to find it on Function's prototype or any other function. It was only available in objects created by the function and I don't know why ?!
@MostafaMahmoud I dont understand, I updated my answer to include examples.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.