2
  • Implementation: 1

    Function.prototype.method = function (name,func){
        this.prototype[name] = func;
         return this;
    };    
    
    String.method('trim', function(){
        return this.replace(/^\s+|\s+$/g, '');
    });  
    
  • Implementation: 2

    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');          
    }  
    

Is there any difference between 1 and 2? except that 1 can be applied to all objects and 2nd is only limited to String objects.

2 Answers 2

1

In both cases only String objects will get the trim function (i.e. the end result will be identical). The first code, as defined, is only a "shortcut" to the second code (I put it in quotes because, in the end, the code length and the effort to implement the first method is roughly the same as the second method).

Sign up to request clarification or add additional context in comments.

Comments

0

A more robust and generic solution for modern browsers :

!Object.implement && Object.defineProperty (Object.prototype, 'implement', {
  // based on http://www.websanova.com/tutorials/javascript/extending-javascript-the-right-way
  value: function (mthd, fnc, cfg) { // adds fnc to prototype under name mthd
      if (typeof mthd === 'function') { // find mthd from function source
        cfg = fnc, fnc = mthd;
        (mthd = (fnc.toString ().match (/^function\s+([a-z$_][\w$]+)/i) || [0, ''])[1]);
      }
      mthd && !this.prototype[mthd] && 
        Object.defineProperty (this.prototype, mthd, {configurable: !!cfg, value: fnc, enumerable: false});
    }
});

// Allows you to do 

String.implement (function trim () { return this.replace(/^\s+|\s+$/g, ''); });

As explained in the referenced web site, this code ensures that the method is properly hidden when iterating over the object properties. It also only adds the method if one does not already exist.

See http://jsfiddle.net/jstoolsmith/nyeeB/

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.