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
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)
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.