【问题标题】:Add method to string class将方法添加到字符串类
【发布时间】:2012-01-13 14:09:46
【问题描述】:

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

   "a".distance("b")

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

【问题讨论】:

  • 有人这样做时叫什么。这是否被认为是猴子修补或其他东西,因为您只是添加了一种新方法?
  • @still_dreaming_1 这叫扩展:stackoverflow.com/questions/3781373/…

标签: javascript


【解决方案1】:

你可以扩展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.

【讨论】:

  • FYI.. 使用this 获取调用此函数的字符串
  • 实际上,对我来说,this 返回一个像String {0: "t", 1: "e", 2: "s", 3: "t", length: 4, [[PrimitiveValue]]: "test"} 这样的对象。要处理实际文本,我必须致电 this.toString()
  • 有什么办法可以用ECMA脚本的方式写“String.prototype.distance = function (char) {}”吗?
  • 扩展原生 JavaScript 对象通常是一种不好的做法。见stackoverflow.com/questions/14034180/…
【解决方案2】:
String.prototype.distance = function( arg ) {
    // code
};

【讨论】:

    【解决方案3】:

    最小示例:

    没有提到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 );
    

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

    【讨论】:

    • 这正是我要寻找的。​​span>
    • 虽然接受的答案是回答原始问题,但这是一个更强的总体通用答案。我不得不问为什么 return(str) vs return str?
    • 我正在为字符串类创建一个新方法,类似于String.prototype.toJadeCase()。这个答案帮助我实现了这一目标。
    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

      你可以这样做:

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

      【讨论】:

      • 这是一个语法错误(你注释掉了你的右花括号):D
      【解决方案6】:

      使用原型将你自己的函数添加到字符串称为原型我创建了可以选择元素并更改其内部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
      

      【讨论】:

        猜你喜欢
        • 2016-11-30
        • 2017-02-24
        • 1970-01-01
        • 1970-01-01
        • 2011-01-03
        • 1970-01-01
        • 2015-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多