0

I'm trying to write a function on which if we pass the string like we do for split, it returns a string which is reversed -

This is what I've tried -

var abc = "hello"
var result;
String.prototype.reverser = function(str){
  var temparr = str.split('').reverse().join('');
  return temparr;
}
result = abc.reverser();
console.log(result);

I'm expecting olleh but rather getting -

VM1179:4 Uncaught TypeError: Cannot read property 'split' of undefined at String.reverser (:4:19) at :7:14

2 Answers2

1

You don't need a parameter str. The string is already binded to the method on prototype. Just use this to access the string.

var abc = "hello"
var result;
String.prototype.reverser = function(){
  return this.split('').reverse().join('');
}
result = abc.reverser();
console.log(result);

Note: You shouldn't directly add enumerable properties to prototype. Instead use Object.defineProperty()

var abc = "hello";
Object.defineProperty(String.prototype,'reverser',{
  value:function(){
    return this.split('').reverse().join('');
  }
})
var result = abc.reverser();
console.log(result)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • Thanks this worked! any documentation or website i can use to read more about this? – SerializedCoffee Jun 23 '19 at 17:27
  • 1
    This would be a good teaching moment for using `Object.defineProperty` rather than creating enumerable properties on built-in prototypes, which is a Bad Idea™. :-) – T.J. Crowder Jun 23 '19 at 17:30
  • @T.J.Crowder I have added that. I can guess why its bad for Objects and Arrays. But what can be side effect for Strings? – Maheer Ali Jun 23 '19 at 17:39
  • Thanks guys! I found this post on why its a bad idea for anyone reading up on this like me - https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice – SerializedCoffee Jun 23 '19 at 17:44
  • 1
    @MaheerAli - You never know when someone will have an actual String object (not primitive) lying around and decide to use a `for-in` loop on it. :-) People do very funny things... – T.J. Crowder Jun 23 '19 at 17:55
  • (BTW, just FWIW, to match the way standard methods are defined, you'd want `writable: true` and `configurable: true` in that `defineProperty` options object.) – T.J. Crowder Jun 23 '19 at 17:56
0

When extending String.prototype with your reverser() function, the string with the new method on it can be accessed with this; the way you have defined it expects an argument (str), that isn't provided. See how this can be used to access the string in this working snip:

var abc = "hello"
var anotherStr = "what do you know?"
var result;
var anotherResult;

String.prototype.reverser = function(){
  var temparr = this.split('').reverse().join('');
  return temparr;
};

result = abc.reverser();
anotherResult = anotherStr.reverser();

console.log(result);
console.log(anotherResult);
JSONaLeo
  • 416
  • 6
  • 11