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

wil*_*ill 51 javascript

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

   "a".distance("b")
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*att 98

你可以扩展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!");
    }
};
Run Code Online (Sandbox Code Playgroud)

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

"Hello".distance("H");
Run Code Online (Sandbox Code Playgroud)

在这里查看JSFiddle.

  • FYI ..使用`this`来获取调用此函数的字符串 (23认同)
  • 实际上,对我来说,`this`返回的对象如`String {0:"t",1:"e",2:"s",3:"t",length:4,[[PrimitiveValue]]:"测试"}`.要使用实际文本,我必须调用`this.toString()` (3认同)
  • 扩展本机JavaScript对象通常是一种不好的做法.请参阅http://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice (2认同)

Wil*_*ill 17

String.prototype.distance = function( arg ) {
    // code
};
Run Code Online (Sandbox Code Playgroud)


J.M*_*SON 11

最小的例子:

没有人提到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]
Run Code Online (Sandbox Code Playgroud)

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

从我对它的研究来看,没有办法就地编辑字符串。

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

下面不起作用并且在调试器中得到非常奇怪的结果。

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

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 );
Run Code Online (Sandbox Code Playgroud)

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

  • 这正是我正在寻找的。 (2认同)

iii*_*iic 8

经过多年(和 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);
Run Code Online (Sandbox Code Playgroud)


JAi*_*iro 6

你可以这样做:

String.prototype.distance = function (){ 
    //your code 
}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个语法错误(您注释掉了右花括号):D (2认同)