Javascript 向字符串类添加方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8392035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:48:41  来源:igfitidea点击:

Add method to string class

javascript

提问by will

I'd like to be able to say something like this in javascript :

我希望能够在 javascript 中说这样的话:

   "a".distance("b")

How can I add my own distance function to the string class?

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

回答by Matt

You can extend the Stringprototype;

您可以扩展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!");
    }
};

... and use it like this;

...并像这样使用它;

"Hello".distance("H");

See a JSFiddle here.

在此处查看 JSFiddle

回答by Will

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

回答by JAiro

You could do this:

你可以这样做:

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

回答by J.M.I. MADISON

Minimalexample:

最小的例子:

No ones mentioned valueOf.

没有人提到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 objectinstead of a string primitive.

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

Below does NOT workand 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 );

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

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

回答by iiic

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

多年后(和 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);

回答by JavaScript

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

使用原型将您自己的函数添加到字符串称为原型我创建了可以选择元素并更改其内部 HTML 的小型 JavaScript 代码

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