


The right way to extend JavaScript functionality (translation)_javascript tips
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 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
});
}

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.