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

1
  • You didn't pass a string into reverser. Commented Jun 23, 2019 at 17:37

2 Answers 2

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)

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

6 Comments

Thanks this worked! any documentation or website i can use to read more about this?
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 I have added that. I can guess why its bad for Objects and Arrays. But what can be side effect for Strings?
Thanks guys! I found this post on why its a bad idea for anyone reading up on this like me - stackoverflow.com/questions/14034180/…
@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...
|
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);

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.