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?

Solid Performer
  • 223
  • 2
  • 4
  • 13
  • 1
    possible duplicate of ["method" method in Crockford's book: Javascript: The Good Parts](http://stackoverflow.com/questions/3966936/method-method-in-crockfords-book-javascript-the-good-parts) – Bergi Nov 19 '13 at 18:24
  • 2
    Did you forget to add `Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; };` from the book? – PSL Nov 19 '13 at 18:24

2 Answers2

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;
};
Andreas
  • 21,535
  • 7
  • 47
  • 56
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.

Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95