Home Web Front-end JS Tutorial Methods of writing JavaScript script libraries_javascript skills

Methods of writing JavaScript script libraries_javascript skills

May 16, 2016 pm 03:27 PM

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(); 
Copy after login

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 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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 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.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

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.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 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.

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

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

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

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.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

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.

See all articles