javascript:将方法添加到string类

我想能够在javascript中这样说:

"a".distance("b") 

我怎样才能将我自己的距离函数添加到string类?

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

在这里看到一个JSFiddle 。

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

你可以这样做:

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

使用原型将自己的函数添加到string称为原型我创build了一个小的JavaScript代码,可以select元素并更改其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