Home Web Front-end JS Tutorial Create your own 'JavaScript library', it turns out to be so easy

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

Apr 02, 2017 pm 04:35 PM

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的代码
}
Copy after login

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,运行的代码
})();
Copy after login

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']['$']=$; 
})();
Copy after login

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>
Copy after login

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库中的函数
Copy after login

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;]=$;
})();
Copy after login

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>
Copy after login

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

##

[object Object]
Copy after login


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>
Copy after login

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>
Copy after login

运行结果,单击"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>
Copy after login

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>
Copy after login

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

文章写到这里,相信您也会编写简单的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 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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

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.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles