Home > Web Front-end > JS Tutorial > The right way to extend JavaScript functionality (translation)_javascript tips

The right way to extend JavaScript functionality (translation)_javascript tips

WBOY
Release: 2016-05-16 17:54:35
Original
1119 people have browsed it

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:

Copy code Code As follows:

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:
Copy code The code is as follows:

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:
Copy code The code is as follows:

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:
Copy code The code is as follows:

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:
Copy code The code is as follows:

var strings = "yay ";
console.log(strings.capitalize)

Will output:
Copy code The code is as follows:

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:
Copy code The code is as follows:

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"
Copy code The code is as follows:

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:
Copy code Code As follows:

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
Copy code The code is as follows :

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
Copy code The code is as follows:

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:
Copy code The code is as follows:

if(!String.prototype.stripTags)
{
Object.defineProperty(String.prototype, ' stripTags',
{
value: function()
{
return this.replace(/] >/gi, '');
} ,
enumerable: false
});
}

String.trim()
Remove leading and trailing spaces:
Copy code The code is as follows:

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:
Copy code The code is as follows:

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
Copy code The code is as follows:

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:
Copy code The code is as follows:

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
});
}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template