I'd like to be able to say something like this in javascript :
"a".distance("b")
How can I add my own distance function to the string class?
add(str1,str2); it should append str1 at the beginning of the string and str2 at the end of the string. This class(inherited string class) is a private member class of another class(say Parent).
A better way to create a function from a string is by using Function : var fn = Function("alert('hello there')"); fn(); This has as advantage / disadvantage that variables in the current scope (if not global) do not apply to the newly constructed function.
distance = function (char) { var index = this. indexOf(char); if (index === -1) { alert(char + " does not appear in " + this); } else { alert(char + " is " + (this. length - index) + " characters from the end of the string!"); } };
Class methods are created with the same syntax as object methods. Use the keyword class to create a class. Always add a constructor() method. Then add any number of methods.
You can extend the String
prototype;
String.prototype.distance = function (char) { var index = this.indexOf(char); if (index === -1) { alert(char + " does not appear in " + this); } else { alert(char + " is " + (this.length - index) + " characters from the end of the string!"); } };
... and use it like this;
"Hello".distance("H");
See a JSFiddle here.
String.prototype.distance = function( arg ) { // code };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With