有没有办法用ECMA脚本方式编写“String.prototype.distance=function(char){}”呢?扩展本机JavaScript对象通常是一种不好的做法。看看有人这样做叫什么。如果你只是添加了一个新方法,那么这算是猴子补丁还是其他什
有没有办法用ECMA脚本方式编写“String.prototype.distance=function(char){}”呢?扩展本机JavaScript对象通常是一种不好的做法。看看有人这样做叫什么。如果你只是添加了一个新方法,那么这算是猴子补丁还是其他什,javascript,Javascript,有没有办法用ECMA脚本方式编写“String.prototype.distance=function(char){}”呢?扩展本机JavaScript对象通常是一种不好的做法。看看有人这样做叫什么。如果你只是添加了一个新方法,那么这算是猴子补丁还是其他什么?@still_dreaming_1它被称为扩展:当有人这样做时,它被称为什么。如果你只是添加了一个新方法,那么这算是猴子修补还是其他什么?@still_dreaming_1它被称为扩展:这正是我要寻找的。虽然被接受的答案回答了最初的问题,但
有没有办法用ECMA脚本方式编写“String.prototype.distance=function(char){}”呢?扩展本机JavaScript对象通常是一种不好的做法。看看有人这样做叫什么。如果你只是添加了一个新方法,那么这算是猴子补丁还是其他什么?@still_dreaming_1它被称为扩展:当有人这样做时,它被称为什么。如果你只是添加了一个新方法,那么这算是猴子修补还是其他什么?@still_dreaming_1它被称为扩展:这正是我要寻找的。虽然被接受的答案回答了最初的问题,但这是一个更强的总体答案。我必须问一下为什么return(str)和return str?我在为string类创建一个新方法,类似于
string.prototype.toJadeCase()
。这个答案帮助我实现了这一目标。这正是我一直在寻找的。虽然被接受的答案回答了最初的问题,但这是一个更强的总体答案。我必须问一下为什么return(str)和return str?我在为string类创建一个新方法,类似于string.prototype.toJadeCase()
。这个答案帮助我做到了这一点。
"a".distance("b")
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");
String.prototype.distance = function( arg ) {
// code
};
String.prototype.distance = function (){
//your code
}
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
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 );