0

I wanna get the next functionality:

var newString = String;
newString.prototype.reverse = function () {
    return this.split("").reverse().join("")
}

var a = 'hello';
var b = newString('hello');
a.reverse();//reverse is not a function
b.reverse();//olleh

try extend .prototype before add function and doesn't work, i don't even know if it is possible.

bugarin
  • 74
  • 2
  • 2
    What's your question? –  Jun 17 '15 at 19:08
  • ["How do you reverse a string in place in JavaScript?"](http://stackoverflow.com/questions/958908/how-do-you-reverse-a-string-in-place-in-javascript) has exactly what you are looking for in some of the lower answers. – JasonWilczak Jun 17 '15 at 19:13
  • 1
    Are you looking for `b.reverse = function(){...}`? – Siguza Jun 17 '15 at 19:15
  • @SLaks you can absolutely do that, and his code works fine as is. There's just no reason to create `newString` if you're augmenting the prototype anyways. – Aweary Jun 17 '15 at 19:16
  • @Aweary: He's trying to _not_ modify normal strings. He can't do that. – SLaks Jun 17 '15 at 19:16
  • reverse it's just an quick example, i wanna get some methods just for 'b', unmodified te prototype String of all my variables. – bugarin Jun 17 '15 at 19:18

2 Answers2

1

You could do the following:

var newString = function(initialVal) {
    var val = new String(initialVal);
    val.reverse = function () {
        return this.split("").reverse().join("")
    };
    return val;
};

var a = 'hello';
var b = newString('hello');
a.reverse();//reverse is not a function
b.reverse();//olleh
David Sherret
  • 101,669
  • 28
  • 188
  • 178
0

It sounds like you're looking for:

String.prototype.reverse = function () {
    return this.split("").reverse().join("")
}

var a = 'hello';
alert(a.reverse());

Note that extending built in objects like "String" is highly controversial at best.

dgavian
  • 250
  • 2
  • 10