ankush981
ankush981

Reputation: 5417

Add method to function

I'm new to JavaScript and am learning from the book JavaScript: The Good Parts. In that book, the following recipe is used to augment a method to all functions:

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

I wanted to explore this concept, so I came up with the following script, which aims to add the greet() method to the func() function:

//define how the augmentation will work
Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
}

//create a dummy function to augment
function func() {
    //do nothing
}

//create function to be added
func.method('greet', function() {
    console.log("Greetings from greet()!");
});

//access the new function
func.greet();

When I run it, though, I get the error Uncaught TypeError: undefined is not a function. Could someone please tell me what I'm doing wrong.

Upvotes: 3

Views: 172

Answers (1)

Phrogz
Phrogz

Reputation: 303224

In this case you want to modify the line:

this.prototype[name] = func;

to just

this[name] = func;

Demo: http://jsfiddle.net/s8aed1bx/1/

Alternatively you could use

this.constructor.prototype[name] = func;

but that would add each new method to every function, not just the one you call method on. Or you could use:

var f2 = new func();
f2.greet();

Why?

When looking up properties on an object in JavaScript, the object itself is searched, and then the prototype of the constructor of the object is searched (and so on up the chain). The .constructor of func is Function.

In this case what you have done would work if you wrote:

func.method('greet', function() {
  console.log("Greetings from greet()!");
});
var f2 = new func();
f2.greet();

The prototype of a function is used for new instances created by that function. (The objects you create have a .constructor of the creating function itself.)

Upvotes: 6

Related Questions