Add method to work

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

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

      

I wanted to learn this concept, so I came up with the following script that aims to add a method greet()

to a function func()

:

//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();

      

I get an error on startup Uncaught TypeError: undefined is not a function

. Can someone please tell me what I am doing wrong.

+3


source to share


1 answer


In this case, you want to change the line:

this.prototype[name] = func;

      

just

this[name] = func;

      

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

Alternatively, you can use

this.constructor.prototype[name] = func;

      

but this will add every new method to every function, not just the one you call method

. Or you can use:



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

      


Why?

When searching for properties of an object, JavaScript looks for the object itself, and then searches for the prototype

object of the constructor

object (and so on down the chain). .constructor

of func

is Function

.

In this case, what you have done will work if you wrote:

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

      

The function prototype is used for new instances created by this function. (The objects you .constructor

create have the very function of creating.)

+6


source







All Articles