Home > Web Front-end > JS Tutorial > body text

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

PHPz
Release: 2017-04-02 16:35:52
Original
1680 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!