admin管理员组

文章数量:1134249

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?

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?

Share Improve this question edited Jun 7, 2019 at 5:01 Herohtar 5,6034 gold badges33 silver badges42 bronze badges asked Dec 5, 2011 at 21:21 willwill 3,1914 gold badges27 silver badges30 bronze badges 2
  • What is it called when someone does this. Is that considered monkey patching or something else sine you are only adding a new method? – still_dreaming_1 Commented Aug 9, 2016 at 15:53
  • @still_dreaming_1 It's called extending: stackoverflow.com/questions/3781373/… – spectre-d Commented Nov 4, 2016 at 19:50
Add a comment  | 

6 Answers 6

Reset to default 161

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
};

Minimal example:

No ones mentioned valueOf.

==================================================

String.prototype.
OPERATES_ON_COPY_OF_STRING = function ( 
    ARGUMENT 
){

    //:Get primitive copy of string:
    var str = this.valueOf();

    //:Append Characters To End:
    str = str + ARGUMENT;

    //:Return modified copy:
    return( str );
};

var a = "[Whatever]";
var b = a.OPERATES_ON_COPY_OF_STRING("[Hi]");
console.log( a ); //: [Whatever]
console.log( b ); //: [Whatever][Hi]

==================================================

From my research into it, there is no way to edit the string in place.

Even if you use a string object instead of a string primitive.

Below does NOT work and get's really weird results in the debugger.

==================================================

String.prototype.
EDIT_IN_PLACE_DOES_NOT_WORK = function ( 
    ARGUMENT 
){

    //:Get string object:
    var str = this;

    //:Append Characters To End:
    var LN = str.length;
    for( var i = 0; i < ARGUMENT.length; i++){
        str[LN+i] = ARGUMENT[ i ];
    };

};

var c = new String( "[Hello]" );
console.log( c );
c.EDIT_IN_PLACE_DOES_NOT_WORK("[World]");
console.log( c );

==================================================

after years (and ES6) … we have a new option how to do this:

Object.defineProperty( String.prototype, 'distance', {
	value: function ( param )
	{
		// your code …
		return 'counting distance between ' + this + ' and ' + param;
	}
} );

// ... and use it like this:
const result = "a".distance( "b" );
console.log(result);

You could do this:

String.prototype.distance = function (){ 
    //your code 
}

Using prototype to add you own function to string is called a prototype I created small JavaScript code that can select elements and change its innerHTML

var dom; //you can replce this to be $ just like jQuery
dom = function(elm) {
if(typeof elm === "object") {
   // already done example 
   //typeof document.getElementById('id') will be object
   return [elm];
 } else {
    return document.querySelectorAll(elm);
 }
} // Returns elements by all css selector eg
// .class #id id p id > p id ~ p in short any css selectors 
 Object.prototype.text = function(txt) {  //object prototype as NodeList returned would be object or maybe displayed as [Object NodeList]
     var i = 0; //loop through the elements 
     for(i; i < this.length; i++) {
        this[i].innerHTML = txt;
      }
 // in this function this refers to object that this function is passed on
 };
 dom('.classh').text('Changed for elements with classh');
 dom('#heading').text('Changed for elements with id heading'); //examples

本文标签: javascriptAdd method to string classStack Overflow