¿Cómo extender JavaScript con un método global como .toLowerCase ()?

I'm trying to find out how to extend JavaScript with some of my own methods similar to toLowerCase()

Say I wanted a capitalize() or addUnderscores(), really whatever. I'm assuming there is a way to extend or overwrite existing ones.

Also is there a way to do it with jQuery?

preguntado el 10 de marzo de 12 a las 02:03

1 Respuestas

Not with jQuery. Just extend the prototype of the specific type you need...

if (!String.prototype.capitalize) {
    String.prototype.capitalize = function() {
        return this.toUpperCase();
    }
}

'foobar'.capitalize(); // 'FOOBAR'

En la función, this will be the string on which you called the method.

respondido 10 mar '12, 02:03

Although I'd assume capitalize ser mas return this.slice(0,1).toUpperCase()+this.slice(1) :) - toque

@tkone: Yeah, that would make more sense. Didn't really think that one through. :) - user1106925

I mean your answer was right in point so like +1 anyway though :) - toque

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.