How to develop native JavaScript plugins (knowledge points + notation)

Source: Internet
Author: User
Tags closure

First, preface

We understand the JavaScript plugin through the "WWW" principle.

The first W "what"-what is it? What is a plugin, I do not copy the abstract concept of the book, my personal simple understanding is that can facilitate the implementation of a function of the extension tool. (I will use simple examples to help the reader understand)

Second W "Why"--why? Why should have the plug-in this kind of thing, first the first W to understand is that the purpose of using the plug-in is to facilitate our implementation of a certain function. That means we just need to find the wheel in the programming process, or change the wheels without having to reinvent the wheel. Save development time and be more professional (do better). Next is the convenience of maintenance, because each function module can be divided more clearly, so-called loose coupling.

How does the third W "how" work? How do we develop JavaScript plugins? That's the point we're going to talk about in this piece of paper.

II. Preparation of knowledge

Before we talk about how to do this, we might as well look at the features of the plugin by reverse thinking. Let's start with how to use the Javascript plugin.

Let's say we're going to use plug-ins js-plugin.js

The first step: introduce plugins, note dependencies, such as some plug-ins are written in jquery, first introduce jquery

Step two: Implement the business we want with the API provided by the plugin

Take the classic jquery use method as an example

<script src= "//cdn.bootcss.com/jquery/3.1.0/jquery.min.js" ></script><script>    $ (function () {        $ ("#Id"). html (' Hello world! ');    }) </script>

By the way, CDN can be used as much as possible, which will allow your resources to load faster. And save your host's bandwidth overhead Portal: BOOTCDN

The above two points in fact is that our plug-in to achieve, the introduction of relevant documents can be easily used. In other words, plugins must meet the following characteristics:

First, I think the most important point of the plugin--reusability. That means you can use this plugin in this project, and it can be used (nonsense) to move to another project, and in principle the fewer dependencies the better

Second, I think this is the purpose of the plugin--ease of use. Development of a plug-in, if the use of cumbersome, rather than re-build the wheel, then lost the meaning of plug-ins.

In addition, of course, there is efficiency, considering the efficiency of execution and memory optimization.

Third, module mode

Plug-in development has to mention the Modlule model, module-module, modular development, is a very common in programming mode. To put it bluntly is to divide the business requirements into modules. Each module is responsible for the implementation of a function. Somewhat like classes in other object-oriented programming languages. For example, Jsonhelper is specifically responsible for JSON parsing, filesupload, specifically for file upload, and so on.

Plug-in is the use of such a modular thinking to develop, the following we have a simple code to explain the next module mode.

var HelloWorld = function (objId) {    var _get_dom = function (ID) {        return document.getElementById (ID);    }    var _aim_obj = _get_dom (objId);    var _say_hello = function (str) {        _aim_obj.innerhtml = str;    }    return{        Sayhello:_say_hello    }}

As shown in the code above, we have some features, such as "SayHello", in the HelloWorld (module). Of course we can continue to add additional functionality below, but all are attributed to module HelloWorld to manage. This is the embodiment of Module.

How to use it (note that new is used here)

var Hei = new HelloWorld (' Hello '); Hei.sayhello (' Hello Word '); var Hei2 = new HelloWorld (' Hi '); Hei2.sayhello (' Hi ');

More intuitively, let's take a look at the complete code.

<! DOCTYPE html>    

The operation results are as follows

What we need to note here is that every new object created by using this will open up new memory space (a new copy), so long as the reference is not freed, the memory space occupied by the object will not be reclaimed. So how do you avoid wasting too much memory? A word "release a reference" is simply to release a reference to the object 所有 , and the garbage collection mechanism reclaims the memory space occupied by that object.

var Hei = new HelloWorld (' Hello '); Hei.sayhello (' Hello World ');    Hei = null;//dereference

This also "manual" Memory management, trouble. How do I get the module to keep only one copy in memory? Take a look at the following code

var HelloWorld = (function () {    var _getdom = function (ID) {        return document.getElementById (ID)                        }    var _ SayHello = function (id,str) {        _getdom (Id). InnerHTML = str;    }    return {        getdom:_getdom,        Sayhello:_sayhello    }} ())

How to use

Helloworld.sayhello (' Hello ', ' Hello text ');

Yes, as you can see, there's no need for new. It is no longer necessary to create a new object when it is used, that is to say, we only keep a reference to the object in memory, that is, the HelloWorld reference to it. The memory occupied by HelloWorld when its reference is lifted will be freed. The code above is essentially an anonymous closure. If the closure is not very understanding of the friends can see I wrote the previous article "Analysis of the closure of JavaScript (Closures)"

Iv. plug-in base code

Now that we understand the above, we're going to start cutting the topic straight.

First we create a JS file named First-js-plugin.js (whatever name is OK), type the following code

var plugin = (function () {    function _firstfunc (str) {        console.log (str);    };    return{        firstfunc: _firstfunc,    };}) ();

Then create an HTML page named plugintest.html (whatever the name is)

The complete code is as follows

<! DOCTYPE html>

Run results as shown

With this simple plugin, let's analyze the code inside.

Before we parse the code, let's start with another thing, calling the anonymous function (preventing plug-in user-defined functions from conflicting with the plugin).

(function () {//code}) ();

Maybe some children's shoes will feel a little strange, then look at the following code

var func = function () {//code} func ();

In fact, these two pieces of code are equivalent, of course, a bit different, the first is an anonymous function. function is to define a function and execute it immediately.

(function () {//code}) ();

Code Analysis:

    1. The last side of the brace () indicates that the function is executed
    2. (anonymous function) parentheses (grouping expressions) wrap up the declaration of an anonymous function, which is equivalent to converting a function declaration to an expression, so that it can be executed, that's all.

      If you take the following wording

      function () {//code} ();

      Compiler error, the problem is that the function declaration cannot be executed, the expression can execute

After we figure this out, we'll go back to the following code to add an analysis, as follows

//javascript Weak grammar features, if there is just one function not to ";" At the end, there may be a syntax error     //Plugin.api_funcs to the object, the property value is the self-invocation anonymous function     here involves the JS scope chain and the knowledge point of the closure    *        /var plugin = ( function () {        function _firstfunc (str) {            alert (str);        };                Return API        return{            firstfunc: _firstfunc        };    }) ();

We extract the code (just to help understand, the friends who have already understood, please ignore)

01. Define variable var plugin = an object;//02. Create an object and return (function () {//code;return ...}) ();///anonymous Execute function return an object//and then look at the return of the core Return{firstfunc: _firstfunc};//that is, a function is stored by a key. Make use of key to access this function var plugin = { Key:function () {//code}}//So the final embodiment is as follows var plugin = {firstfunc: "Specific function Reference"}

So we finally get through, 插件名.属性 using plugins, just like:

Plugin.firstfunc ("Hello! I am Firstfunc ");

Iv. several types of plugins

Here I will not ink, directly on the code, the key point will give the comment

  1. Object-Oriented thought class mode

    Custom class    Function plugin () {}//provides default parameters plugin.prototype.str = "default Param";//provides methods (default parameters are used if no parameters are passed) Plugin.prototype.firstFunc = function (str = THIS.STR) {    alert (str);} Create "Object" var p = new plugin ();//Call Method P.firstfunc ("Hello! I am Firstfunc ");//hello! I am Firstfuncp.firstfunc ();//default param
  2. Closure method

    Closures are just the way we've been introducing

    var plugin = (function () {    function _firstfunc (str) {        alert (str);    };    return{        firstfunc: _firstfunc,    };}) ();

  3. Some changes in the second way

    (function () {    ///define some default parameters    var _options={        default_word: "Default Hello"                    }    //define some API    var _plugin_api = {        firstfunc:function (str = _options.default_word) {            alert (str);            Return this;//returns the current method        },        secondfunc:function () {            alert ("Secondfunc");            Return this;//returns the current method        }    }    //The name of the plugin is determined here    . Cjplugin = _plugin_api;}) (); Cjplugin.firstfunc ("Hello");//hellocjplugin.firstfunc ();//default Hellocjplugin.secondfunc ();//secondFunc
Conclusion

Knowledge of JavaScript plugin for the time being today. In the next article, I will introduce an example of how to develop a three-level linkage plug-in. If a friend is learning plugin development. So the next article maybe we have more topics to discuss.

Limited to the author's technology, the article will inevitably have inappropriate points, hope to find a friend to help correct the problem, the author would be updated in a timely manner. Please also reprint of friends to indicate the source of the article and attached to the original link, so that readers can timely access to the article updated content, so as not to mislead readers. The author tries to avoid writing obscure articles (although some people say that it seems high-cornered, professional), try to use simple words and examples to help understand. If there are good suggestions in the expression, I hope friends will point out in the comment office.

How to develop native JavaScript plugins (knowledge points + notation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.