javascript:将方法添加到字符串类

时间:2011-12-05 21:21:10

标签: javascript

我希望能在javascript中说出类似的内容:

   "a".distance("b")

如何将自己的距离函数添加到字符串类?

6 个答案:

答案 0 :(得分:87)

您可以扩展String原型;

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!");
    }
};

......并像这样使用它;

"Hello".distance("H");

See a JSFiddle here

答案 1 :(得分:15)

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

答案 2 :(得分:5)

你可以这样做:

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

答案 3 :(得分:3)

使用prototype将自己的函数添加到字符串中称为原型我创建了一些小的JavaScript代码,可以选择元素并更改其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

答案 4 :(得分:0)

最小示例:

没有人提到 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]

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

从我的研究中,没有办法编辑字符串。

即使您使用字符串对象而不是字符串原语。

下方无法正常工作,并且在调试器中获得了非常奇怪的结果。

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

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

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

答案 5 :(得分:0)

几年后(和ES6)……我们有一个新的选择方式:

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