abbood
abbood

Reputation: 23548

how to define a custom method on the javascript object class

I was going over Javascript the good parts and I came across this example, where the author was trying to explain how to be able to call a superclass:

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

an example of using this code:

super_get_name = that.superior('get_name');

however chrome wouldn't recognize method on Object. I tried doing the same thing using defineProperty but that didn't work either.. any help?

update: does this method cause any known conflicts with jQuery? As soon as i put the following at the first js file in my page:

I get this error in line 2062 in jquery-1.11.0.js:

Uncaught TypeError: Object function (name) {
    var that = this,
        method = that[name];
    return function (  ) {
        return method.apply(that, arguments);
    };
} has no method 'exec' 

this is the effected code:

    // Filters
    for ( type in Expr.filter ) {
        if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
            (match = preFilters[ type ]( match ))) ) {
            matched = match.shift();
            tokens.push({
                value: matched,
                type: type,
                matches: match
            });
            soFar = soFar.slice( matched.length );
        }
    }

any idea what's going on?

Upvotes: 0

Views: 435

Answers (2)

Bergi
Bergi

Reputation: 664307

seems that using that messes up my jquery.. is there a way to avoid it?

Yes. Redefine Function.prototype.method to

Function.prototype.method = function (name, func) {
  Object.defineProperty(this.prototype, name, {
    configurable: true,
    enumerable: false, // sic!
    writable: true,
    value: func
  });
  return this;
};

before using it on the Object function (Function.prototype.method itself doesn't mess up jQuery, but calling Object.method() does). See also How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop.

Upvotes: 2

Emilio Rodriguez
Emilio Rodriguez

Reputation: 5749

The author of the book explains that for that piece of code to work you need to define the method function first:

Throughout the book, a method method is used to define new methods. This is its definition:

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

Upvotes: 4

Related Questions