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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)