search
HomeWeb Front-endJS TutorialCreate your own 'JavaScript library', it turns out to be so easy

JavaScript library is actually a collection of functions, which are convenient for you to call without having to write those powerful functions yourself... This article talks about how to create a JavaScript library and what you need to pay attention to. question! Looking forward to your visit!

Contents:

Issues to note when writing JavaScript libraries

Writing Template code of JavaScript library

Write JavaScript library (example)

Perfect JavaScript library (example)

1. Issues to pay attention to when writing JavaScript libraries

In order to make our JS library more elegant and reasonable, we write JS libraries Please pay attention to two aspects:

1. Do not use version detection, but use capability detection

Because there are too many types and versions of browsers, and new browsers are constantly emerging. , it is impossible for us to invest a lot of time and cost to practice detecting various versions of browsers. "Browser detection" also called "version detection" is often considered a wrong practice. The best practice for browser detection is capability detection, also commonly known as object detection, which refers to detecting an object before the code is executed. The presence or absence of a script object or method does not depend on your specific knowledge of which browser. If the necessary objects and methods exist, then the browser can use it and the code can execute as expected. Capability detection uses the method of

// JavaScript Document
if(document.body && document.body.getElementsByTagName){
//使用document.body.getElementsByTagName的代码
}

2. Using namespace

When using multiple js library files, in order to avoid using different js libraries when calling Conflicts between files with the same name are generally resolved using namespaces. JavaScript supports functions with the same name, but only uses the last loaded function (overloading is not supported, parameters are not considered, only the function name is looked at), whichever one is loaded last will be called. Therefore, if you do not use a namespace, it is easy to encounter the problem of function conflicts with the same name.

Two principles for using namespaces: uniqueness and no sharing.

Uniqueness: Pick a unique namespace name (for example, Google Maps adds the G prefix to all identifiers). Note that js is case-sensitive.

No sharing: No sharing means sharing nothing; when you create your own $function, you may conflict with the $function in a well-known library (such as Prototype), causing the $function in Prototype to fail. Use, in order not to conflict with some well-known libraries (jQuery, prototype) or other existing functions, use anonymous functions to achieve non-sharing of code. For example: To ensure that only you use this $() function, you can use a JS trick.

//匿名函数
(function(){
//code,运行的代码
})();

Note: () It has two meanings in JavaScript: one is the operator; the other is the delimiter.

Two points need to be explained about the anonymous function above:

①The red brackets are an anonymous function. The red brackets represent division, indicating that the function inside is a part;

②Green Brackets represent an operator, indicating that the function inside the red brackets needs to be run; it is equivalent to letting it run directly after defining an anonymous function.

2. Write JavaScript library template

1. You can use the following template to write your own JavaScript library

//JavaScript库模板代码
(function (){
function $(){
alert("被调用到喽!"); 
/*alert()是JavaScript脚本语言中窗口window对象的一个常用方法;
其主要用法就是在你自己定义了一定的函数以后,通过执行相应的操作,
所弹出对话框的语言。并且alert对话框通常用于一些对用户的提示信息。*/ 
}
 //注册命名空间 'myNameSpace' 到window对象上  
            window['myNameSpace'] = {}  
          
 //把$函数注册到 'myNameSpace'命名空间中
 window['myNameSpace']['$']=$; 
})();

2. On the HTML page How to quote the function in your own JS library:

First, execute "Insert→HTML→Script Object→Script", search for the js library file you want to insert into this HTML page and insert it under the HTML file title, for example

<title>ICTest</title>
<!--此处通过执行"插入→HTML→脚本对象→脚本",搜素自己要插入到此HTML页的js库文件插入此位置-->
<script language="JavaScript" type="text/javascript" src="IC.js"></script>

Then, call the function in the JS library in the body attribute, two ways

①<body onload="myNameSpace.$()"></body>   //myNameSpace为定义的命名空间,可以调用自己构建的JS库文件中到函数了
②<body onload="window.myNameSpace.$()"></body> //在命名空间前加上window也可实现调用JS库中的函数

3. Write your own JavaScript library (example)

Implement a simple example of popping up a dialog box when a web page is loaded. In this example, we use the programming software Dreamweaver 8.

1. Create your own JS library. I named the namespace WALY.js here.

Note: Everyone can use their favorite name as the name of the namespace, so that there will be no mutual interference even when libraries written by others are used together.

//ZAJ.js库代码
(function (){
function $(){
alert("AZJ.js库被调用到喽!"); 
}
 //注册命名空间 &#39;AZJ&#39; 到window对象上  
            window[&#39;AZJ&#39;] = {}      
 //把$函数注册到 &#39;AZJ&#39;命名空间中
 window[&#39;AZJ&#39;][&#39;$&#39;]=$;
})();

2. Call the JS library in the HTML page code to verify whether the function in WALY.js is called. The name of the HTML file is WALYTest.html

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>调用js库测试</title>
<!--此处通过执行"插入→HTML→脚本对象→脚本",搜素自己要插入到此HTML页的js库文件插入此位置-->
<script language="JavaScript" type="text/javascript" src="AZJ.js"></script>
</head>
<body onload="AZJ.$();"> <!--在页面加载时,调用AZJ.js库中的函数;这里也可使用<body onload="window.AZJ.$();">-->
</body>

3. Run the web page, the running result is as shown in the figure

##

[object Object]


4. Improve the JavaScript library

##Here we mainly write two commonly used methods in the JS library anonymous function:

1.$()方法
2.getElementsByClassName()方法
实例初探:js库中只编写$()方法
1.建立"AZJ.js"库,编写$()方法,代码如下
//ZAJ.js库代码
(function (){
   //注册命名空间 &#39;AZJ&#39; 到window对象上  
        window[&#39;AZJ&#39;] = {} 
   //$函数等同于getElementByID;
function $(){
var elements=new Array(); 
//将传来的参数进行遍历
for(var i=0;i<arguments.length;i++){
var element=arguments[i];
//若参数为字符串类型,则取得该参数的id
if(typeof element==&#39;string&#39;){
element=document.getElementById(element);
}
//若参数长度为1,即只传递进来一个参数,则直接返回
if(arguments.length==1){
return element;
}
//若有多个参数传递进来,则将处理后的值压入elements数组中
elements.push(element);
}
//返回处理后的参数
return elements;
}
 
          
 //把创建的函数$注册到 &#39;window.AZJ&#39;命名空间中
 window[&#39;AZJ&#39;][&#39;$&#39;]=$;
          
})();
2.在HTML页面进行测试
当从界面只传递一个参数时,代码设计
<title>调用js库测试</title>
<!--此处通过执行"插入→HTML→脚本对象→脚本",搜素自己要插入到此HTML页的js库文件插入此位置-->
<script language="JavaScript" type="text/javascript" src="AZJ.js"></script>
<script language="JavaScript" type="text/javascript" >
function testClick(){
var testInput=AZJ.$("testID");
alert(testInput.value);
}
</script>
</head>
<body >
<input type="text" value="AZJtest" id="testID"/>
<input type="button" value="Click Me" onclick="testClick()"/>
</body>

The running result is: click the "Click Me" button and a pop-up will appear. Web message: AZJtest

当从界面传递两个参数时,代码设计

<span style="font-family:FangSong_GB2312;font-size:18px;"><title>调用js库测试</title>  
<!--此处通过执行"插入→HTML→脚本对象→脚本",搜素自己要插入到此HTML页的js库文件插入此位置-->  
<script language="JavaScript" type="text/javascript" src="AZJ.js"></script>  
<script language="JavaScript" type="text/javascript" >  
    function testClick(){  
        var testInput=AZJ.$("testID","testID2");  
        //由于这里是两个参数,所以用for语句遍历两个参数,分别显示出来  
        for(var i=0;i<testInput.length;i++){  
        alert(testInput[i].value);  
        }  
          
    }  
</script>  
</head>  
<body >  
<input type="text" value="AZJtest" id="testID"/>  
<input type="text" value="AZJtest2" id="testID2"/>  
<input type="button" value="Click Me" onclick="testClick()"/>  
</body></span>

运行结果,单击"Click Me"按钮,先弹出AZJtest,再弹出AZJtest2

Create your own JavaScript library, it turns out to be so easy

实例深入:编写getElementByClassName()方法

1.在"AZJ.js"库中编写getElementByClassName()方法,代码设计如下

<span style="font-family:FangSong_GB2312;font-size:18px;">//ZAJ.js库代码  
    (function (){  
        //注册命名空间 &#39;AZJ&#39; 到window对象上    
        window[&#39;AZJ&#39;] = {}   
          
          //getElementsByClassName包含两个参数:类名,标签名  
          function getElementsByClassName(className,tag){  
              //对tag进行过滤,取出所有对象,如取出所有input类型对象。  
              var allTags=document.getElementsByTagName(tag);  
              var matchingElements=new Array();  
                
              //正则表达式  
              className = className.replace(/\-/g,"\\-");  
              var regex = new RegExp("(^|\\s)" +className+ "(\\s|$)");  
                
              var element;  
                
              //将取出的tag对象存入数组中。  
              for(var i=0;i<allTags.length;i++){  
                  element =allTags[i];  
                  if(regex.test(element.className)){  
                      matchingElements.push(element);  
                      }  
                  }  
              return matchingElements;  
              }  
          //把创建的函数getElementsByClassName注册到 &#39;window.AZJ&#39;命名空间中  
          window[&#39;AZJ&#39;][&#39;getElementsByClassName&#39;]=getElementsByClassName;  
        })();</span>

2.在HTML页面进行测试

测试方式同上面传递两个参数的方式,代码设计如下

<span style="font-family:FangSong_GB2312;font-size:18px;"><title>调用js库测试</title>  
<!--此处通过执行"插入→HTML→脚本对象→脚本",搜素自己要插入到此HTML页的js库文件插入此位置-->  
<script language="JavaScript" type="text/javascript" src="AZJ.js"></script>  
<script language="JavaScript" type="text/javascript" >  
    function testClick(){  
        var testInput=AZJ.getElementsByClassName("testme","input");  
        //由于这里是两个参数,所以用for语句遍历两个参数,分别显示出来  
        for(var i=0;i<testInput.length;i++){  
        alert(testInput[i].value);  
        }  
          
    }  
</script>  
</head>  
<body >  
<input type="text" value="AZJtest" class ="testme" id="testID"/>  
<input type="text" value="AZJtest2" class="testme" id="testID2"/>  
<input type="button" value="Click Me" onclick="testClick()"/>  
</body></span>

运行结果,同上述方法中传递两个参数的情况。

文章写到这里,相信您也会编写简单的js库文件了吧,编写js库文件是不是很简单呢

The above is the detailed content of Create your own 'JavaScript library', it turns out to be so easy. For more information, please follow other related articles on the PHP Chinese website!

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

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.