js原生插件格式解析

一个合格的插件必须满足以下要求:

1.拥有独立作用域与用户作用域隔离,插件内的私有变量不可影响用户定义的变量

2.拥有默认参数

3.提供配置方法让用户可改变参数

4.提供监听接口,以监听页面操作

5.支持链式调用

接下来是一个改变文本颜色的简单插件

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <p class="a">11</p>
        <input type="button" class="clickIt"/>
    </body>
    <script>
        //自执行函数内变量拥有独立作用域并与外界隔离
        (function(){
            //默认参数写在最前面
            var obj = ''
            //参数方法API
            var api = {
                //配置方法改变参数
                config: function (opt) {
                    obj= document.querySelector(opt)
                    //返回this对象,其指向调用此方法的对象,故可以链式调用
                    return this
                },
                //监听页面操作
                listen: function listen(elem) {
                    document.querySelector(elem).onclick= ()=> {
                        this.fun1(obj)
                    }
                    return this
                },
                fun1: function(obj) {
                    obj.style.color= "red"
                    return this
                }
            }
            //this为window对象,simplePlugin为插件名称
            this.simplePlugin= api
        })()
    </script>
    <script>
        simplePlugin.config('.a').listen(".clickIt")
    </script>
</html>

另一种格式是通过构造函数创建实例:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <p class="a">11</p>
        <input type="button" class="clickIt"/>
    </body>
    <script>
        //自执行函数内变量拥有独立作用域并与外界隔离
        (function(){
            function api(){
                this.obj= ''
                this.config= (opt)=> {
                    obj= document.querySelector(opt)
                    //返回this对象,其指向调用此方法的对象,故可以链式调用
                    return this
                }
                //监听页面操作
                this.listen= (elem)=> {
                    document.querySelector(elem).onclick= ()=> {
                        this.fun1(obj)
                    }
                    return this
                }
                this.fun1= (obj)=> {
                    obj.style.color= "red"
                    return this
                }
            }
            //this为window对象,simplePlugin为插件名称
            this.simplePlugin= api
        })()
    </script>
    <script>
        var sp= new simplePlugin()
        sp.config('.a').listen(".clickIt")
    </script>
</html>

 

转载于:https://www.cnblogs.com/yanze/p/7459008.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值