Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use prototype in javascript thatinherit from string Object and implements custom function

I have a funtionas follow,

function revStr(s) {
    ns = '';

    for (i = s.length - 1; i >= 0; i--)
    ns += s[i];
    alert(ns);
}

I have been asked to implement this using Prototype which I am totally unaware of in Javascript(I am a phpdeveloper:( )

I have to create an object that inherits from a string object . Which I think we can do something like this

var MyString= new string();

and then implement my function revStr using somethingcalled Prototype in javascript

Can anyone help me out in this .

Thanks

like image 708
Vikram Anand Bhushan Avatar asked Mar 13 '26 20:03

Vikram Anand Bhushan


1 Answers

That means you want to add revStr() to the String.prototype, so basically all strings can do revStr().

You can implement the function to the string prototype by:

String.prototype.revStr = function(){
    ns = '';
    for (i = this.length - 1; i >= 0; i--)
        ns += this[i];
    alert(ns);
}

So you can use this function on any string afterwards like this:

'hello world'.revStr();
'fooobarrrr'.revStr();
like image 161
TaoPR Avatar answered Mar 16 '26 08:03

TaoPR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!