How to use prototype in javascript that inherits from string Object and implements a custom function
I have funtionas,
function revStr(s) {
ns = '';
for (i = s.length - 1; i >= 0; i--)
ns += s[i];
alert(ns);
}
I was asked to implement this using Prototype, which I am completely unaware of in Javascript (I am phpdeveloper :()
I need to create an object that inherits from a string object. What I think we can do something like this
var MyString= new string();
and then implement my function revStr
with somethingcalled Prototype
in javascript
Can anyone help me on this.
thank
source to share
This means what you want to add revStr()
to String.prototype
, so basically all lines can execute revStr()
.
You can implement this function on a string prototype:
String.prototype.revStr = function(){
ns = '';
for (i = this.length - 1; i >= 0; i--)
ns += this[i];
alert(ns);
}
So, you can use this function for any line after that like this:
'hello world'.revStr();
'fooobarrrr'.revStr();
source to share
I need to create an object that inherits from a string object ... implement my revStr function with somethingcalled Prototype in javascript
It's simple. Just make changes to String.prototype
All String instances inherit from String.prototype. The functions available to the String prototype object are available to all String instances.
String.prototype.revStr = function(s){
ns = '';
for (i = s.length - 1; i >= 0; i--)
ns += s[i];
alert(ns);
}
This way, if you do var obj = new String()
, the newly created object obj
will prototypically inherit the method revStr
defined on String.prototype
, and the call obj.revStr("abcd")
will return"dcba"
JavaScript has only one construct when it comes to inheritance: objects. Each object has an internal reference to another object called its prototype. When trying to access an object object, the property will search not only the object, but also the object prototype, prototype prototype, etc., until a property with the corresponding name is found or the end of the prototype chain is reached
You can read more about prototypal inheritance from MDN docs
source to share