search
HomeWeb Front-endJS TutorialMethods of writing JavaScript script libraries_javascript skills

JavaScript is what is called a client-side scripting language, a computer programming language that runs inside an Internet browser (a browser is also called a Web client because it connects to a Web server to download pages). JavaScript works in an interesting way. Some JavaScript code will be inserted into ordinary web pages. When the browser loads the page, the browser's built-in interpreter reads and runs the JavaScript code it finds in the page.

I have been doing web development for four years and have more or less accumulated some JavaScript scripts. For example, a script that limits input to only allow numbers to be entered; hitting Enter will automatically go to the next control, which is equivalent to the function of the Tab key; because the results of JavaScript numerical operations are often not what we want, floating point operations are also required (plus subtraction, multiplication and division) functions. Every time there is a need for JavaScript, I often find the required script on the Internet, copy it directly into an aspx file, or create a new JavaScript file and add a reference
, in this way to complete the production of client-side scripts. After all, there is not much demand for JavaScript, so I don’t put a lot of effort into learning it.

I’m not busy with the company’s projects recently, so I’m going to catch up on my script knowledge in my free time. There is a very popular JQuery script library on the Internet, and there are a lot of articles in the garden discussing how to use it. From my personal experience, JavaScript, like regular expressions, is often learned and often forgotten. If you don’t use the knowledge you have learned, you will soon forget it. Especially application-related content, such as how to use PageMethods, how to implement client short callbacks, and how to use JavaScript to call Web services. I have used it many times in the project, but when asked by colleagues, it is still vague and difficult to explain. This is why. One way I have is to make demos, make demos with various effects, put them together in categories, and then search for them when using them. This can save a lot of time. Another method is mentioned in today's article, which is to organize the JavaScript you have done and make it into a more general script library for easy reuse. The meaning of organizing is to make appropriate adjustments to the function so that it can not only meet the needs of the current project, but also meet the needs of future projects. Another meaning is to standardize the naming and organizational structure, write sample code, and use Convenient when getting up. Sometimes I download a lot of useful JavaScript scripts from the Internet, but forget to download its test scripts and don’t know how to use them. It is better to search again on the Internet.

JavaScript is defined as an object-based scripting language. On the one hand, it is based on the DOM object model and methods in DOM objects. On the other hand, it does not have the inheritance and polymorphism characteristics of object-oriented languages. ASP.NET AJAX extends JavaScript so that we can organize JavaScript scripts in an object-oriented manner. My main job here is encapsulation, encapsulating existing code to facilitate reuse next time. So, there are two ways to organize your existing JavaScript code base.
I take the controversial addition and subtraction operations in floating point operations in JavaScript as an example to see how to encapsulate them

JavaScript style

function Math() { } 
//加法 
Math.prototype.Add=function(arg1,arg2){ 
var r1,r2,m; 
try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} 
try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} 
m=Math.pow(10,Math.max(r1,r2)) 
return (arg1*m+arg2*m)/m 
} 
//减法 
Math.prototype.Subtraction=function(arg1,arg2){ 
  var r1,r2,m,n; 
  try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} 
  try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} 
  m=Math.pow(10,Math.max(r1,r2)); 
  n=(r1>=r2)?r1:r2; 
  return ((arg1*m-arg2*m)/m).toFixed(n); 
} 
调用方式 
var math=new Math(); 
var result=math.Add(2.0,4.0); 
AJAX风格 
Type.registerNamespace(“Utility”); 
Utility.Math=function(larg,rarg) 
{ 
 this._left=larg; 
 this._right=rarg; 
} 
Utility.Math.prototype= 
{ 
//加法函数 
Add:function () 
{ 
var r1,r2,m; 
try{r1=left.toString().split(".")[1].length}catch(e){r1=0} 
try{r2=right.toString().split(".")[1].length}catch(e){r2=0} 
m=Math.pow(10,Math.max(r1,r2)) 
return (left*m+right*m)/m 
} 
//减法函数 
Subtraction: function(){ 
  var r1,r2,m,n; 
  try{r1=left.toString().split(".")[1].length}catch(e){r1=0} 
  try{r2=right.toString().split(".")[1].length}catch(e){r2=0} 
  m=Math.pow(10,Math.max(r1,r2)); 
  n=(r1>=r2)?r1:r2; 
  return ((left*m-right*m)/m).toFixed(n); 
} 
} 
//注册类 
Utility.Math.registerClass(“Utility.Math”); 
然后,在需要的地方,就可以运用下面的方法调用 
var math=new Utility.Math(2.0,4.2); 
var result=math.Add(); 

Using the two methods proposed above can easily encapsulate commonly used JavaScript and reduce duplication.

There is a problem with the naming above, because Math is a type built into JavaScript and is used to handle various mathematical operations. In order to make the above JavaScript-style script run, the class name must be replaced with another name. Such as MathHelper. ASP.NET AJAX also extends the six types of JavaScript, namely Array, Boolean, Date, Error, Object and string.

Now that you have the method, some friends may say that you should publish the JavaScript library you made so that it can satisfy the public's taste. With this method alone, it is still very difficult to put it into practice: there are reasons for tight project schedules, busy working on projects every day, and there is no time to organize this, and there are also reasons for not being familiar with JavaScript.

In order to prevent my class library from being useless, I went online to find some advice on writing good JavaScript libraries.

There is an article called "Building a JavaScript Library". Before writing this article, I wanted to see how he wrote it, but the web page kept saying that the file was being loaded and could not be viewed. I really want to know how foreigners write about the same theme.

There is also an excellent article called "Rules For JavaScript Library Authors", located at
http://dean.edwards.name/weblog/2007/03/rules/

I translated it for your reference

1 Don’t be too cumbersome in how to use it.
2 Avoid using Object.prototype
3 Don’t overextend
4 Comply with standards.
5 Follow the example of excellent JavaScript creators
6. Stay flexible. 7. Manage memory well to avoid memory leaks.
8 Avoid browser-related hacks
9 Keep the class library simple
10. Keep libraries predictable. For example, even without checking the documentation, you should be able to guess that Math deals with content related to mathematical operations
11 Extra points rules: documentation; use as many namespaces as possible to organize code to make it easy to remember;

My level is very average, a very ordinary programmer. So, don't ask me for code. I gave it to you, but you still have to take the time to read it; and my code has no documentation, so what should you do if you can’t read it? Instead of doing this, why not sort out the JavaScript you have on hand? Besides, the JavaScript you have on hand has been actually used by you, so you must be familiar with it. Don't recommend JQuery either, it's not my purpose.
My goal is to teach you how to organize your existing JavaScript script library and make good use of the resources you already have.

Test code download: http://xiazai.jb51.net/201509/yuanma/Math-Test(jb51.net).rar

To add a common problem: if you put JavaScript in an external file, you may get a prompt of "Object not found" when running
This problem is caused by the file encoding. Keep the encoding of JavaScript script files consistent with the file encoding of HTML pages
Click File-->Save as option to save both in the same encoding format

It is recommended to use VS IDE to write scripts, so that you can use the smart prompt support provided by the IDE

If you use Dreamweaver to write scripts, it also provides smart prompts


The above content introduces you to the method of writing JavaScript script library. I hope you like it.

Statement
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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor