I saw the article "JavaScript Weekly Introduction" [Issue 3] this morning, and found an article in it (Extending JavaScript – The Right Way), which I thought was pretty good, translated Come and share it with everyone. This article is not translated word for word. I try to make it as easy to understand as possible.
Original address: Extending JavaScript – The Right Way
The following is the translation
JavaScript has built-in many powerful methods, but sometimes A certain function you need is not available in the built-in method. How can we extend JavaScript functions elegantly?
For example, we want to add a capitalize() method to capitalize the first letter. Usually we write it like this:
if(!String.prototype.capitalize)
{
String.prototype.capitalize = function()
{
return this.slice(0, 1).toUpperCase() this.slice(1).toLowerCase();
}
}
The above code can be used normally, but if there is the following somewhere Code:
var strings = "yay";
for(i in strings) console.log(i ":" strings[i]);
The result we get is this:
0: y
1: a
2: y
capitalize: function () { return this.slice(0, 1).toUpperCase() this.slice(1).toLowerCase(); }
This is obviously not the result we want , the reason why the method we added is output is that the enumerable attribute of the method we added defaults to true.
We can avoid this problem by simply setting the enumeration property (enumerable) to false and use the defineProperty method to extend the functionality:
if(!String.prototype.capitalize)
{
Object.defineProperty(String.prototype, 'capitalize',
{
value: function()
{
return this.slice(0,1).toUpperCase() this.slice(1).toLowerCase();
},
enumerable: false
});
}
Now we run this code again:
var strings = "yay";
for(i in strings) console.log(i ":" strings[i]);
The result we get is:
0: y
1: a
2: y
It should be noted that the lack of output through the loop does not mean that it does not exist. We can pass See the definition in the following code:
var strings = "yay ";
console.log(strings.capitalize)
Will output:
function () { return this.slice(0, 1).toUpperCase() this.slice(1).toLowerCase(); }
It is more flexible to extend JavaScript functions in this way. We can use this way to define our own objects and set some default values.
The following are several other extension methods that you can use in your own projects:
String.pxToInt()
Convert a string like "200px" into the number 200:
if(!String.prototype.pxToInt)
{
Object. defineProperty(String.prototype, 'pxToInt',
{
value: function()
{
return parseInt(this.split('px')[0]);
},
enumerable: false
});
}
String.isHex()
Determine whether a string is expressed in hexadecimal, such as "#CCC" or "#CACACA"
if(!String.prototype.isHex)
{
Object.defineProperty(String.prototype, 'isHex',
{
value: function()
{
return this.substring(0,1) == '#' &&
(this.length == 4 || this.length == 7) &&
/^[0-9a-fA-F] $/.test(this.slice(1));
},
enumerable: false
});
}
String.reverse()
String reverse:
if(!String.prototype.reverse)
{
Object.defineProperty(String.prototype, 'reverse',
{
value: function( )
{
return this.split( '' ).reverse().join( '' );
},
enumerable: false
});
}
String.wordCount()
Count the number of words, separated by spaces
if(!String.prototype.wordCount)
{
Object.defineProperty(String.prototype, 'wordCount',
{
value: function()
{
return this.split(' ').length;
},
enumerable: false
});
}
String. htmlEntities()
HTML tags such as < and > are encoded as special characters
if(!String.prototype.htmlEntities)
{
Object.defineProperty(String.prototype, 'htmlEntities',
{
value: function()
{
return String(this).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
},
enumerable: false
});
}
String.stripTags()
Remove HTML tags:
if(!String.prototype.stripTags)
{
Object.defineProperty(String.prototype, ' stripTags',
{
value: function()
{
return this.replace(/?[^>] >/gi, '');
} ,
enumerable: false
});
}
String.trim()
Remove leading and trailing spaces:
if(!String.prototype.trim)
{
Object.defineProperty(String.prototype, 'trim',
{
value: function()
{
return this.replace(/^s*/, "").replace(/s*$/, "");
},
enumerable: false
});
}
String.stripNonAlpha()
Remove non-alphabetic characters:
if(!String.prototype.stripNonAlpha)
{
Object.defineProperty (String.prototype, 'stripNonAlpha',
{
value: function()
{
return this.replace(/[^A-Za-z ] /g, "");
},
enumerable: false
});
}
Object.sizeof()
Count the size of objects, such as {one: “and”, two: "and"} is 2
if(!Object .prototype.sizeof)
{
Object.defineProperty(Object.prototype, 'sizeof',
{
value: function()
{
var counter = 0;
for(index in this) counter ;
return counter;
},
enumerable: false
});
}
It is quite good to extend the functions of JS native objects in this way, but unless necessary (used a lot in projects), it is not recommended to directly extend functions on native objects, which will cause global variable pollution.
In addition, the pxToInt() method in the article is not necessary. parseInt() in JS can directly complete such a function: parsetInt("200px")===200
There seems to be a problem with the htmlEntities method. Here is another Provide one:
if(!String.prototype.htmlEntities)
{
Object.defineProperty(String.prototype, 'htmlEntities',
{
value: function()
{
var div = document.createElement("div");
if(div.textContent){
div.textContent=this;
}
else{
div.innerText=this;
}
return div.innerHTML;
},
enumerable: false
});
}