0

Going through the example code for chapter 5.4 in Javascript: The Good Parts, the following is used to demonstrate the use of the functional pattern to call super methods:

Object.method('superior', function (name) {
    var that = this, method = that[name];
    return function () {
        return method.apply(that, arguments);
    };
});

This would be used as follows (where "cat" is another constructor function that has a 'get_name' function defined) :

var coolcat = function (spec) {
    var that = cat(spec),
        super_get_name = that.superior('get_name');
    that.get_name = function (n) {
        return 'like ' + super_get_name(  ) + ' baby';
    };
    return that;
};

However when running the sample code, F12 tools show the following:

Uncaught TypeError: Object function Object() { [native code] } has no method 'method'.

What am I missing here?

2
  • 1
    possible duplicate of "method" method in Crockford's book: Javascript: The Good Parts Commented Nov 19, 2013 at 18:24
  • 2
    Did you forget to add Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; }; from the book? Commented Nov 19, 2013 at 18:24

2 Answers 2

4

Douglas Crockford uses the following (defined on page 4 of the book)

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};
Sign up to request clarification or add additional context in comments.

Comments

1

That's because the method method is not defined in your code, check the book for a place where the author defined the method method.

Apparently @Andreas has found the method, and now I remember it.

The method method is used so that when it is called on any object, it defines a method on that object where the name of that method is the name parameter passed to method, and the implementation of that method is the func function parameter.

You need to include this in your console for things to work correctly.

Comments

Your Answer

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.