$.extend()使用详解

jQuery为开发插件提拱了两个方法,分别是: 
jQuery.fn.extend(object); 
jQuery.extend(object); 


jQuery.extend(object);为扩展jQuery类本身.为类添加新的方法。 
jQuery.fn.extend(object);给jQuery对象添加方法。

 

举个例子。

<span style="font-size:18px;"><html> 
<head> 
<title></title> 
</head> 
<body> 
<h3 class="ye">new soul</h3> 
<h3 class="ye">new soul</h3> 
<h3 class="ye">new soul</h3> 
<h3 class="ye">new soul</h3> 
<script type="text/javascript" src="jquery.2.0.3.js"></script> 
<script type="text/javascript"> 
jQuery.fn.myPlugin = function(options) { 
$options = $.extend( { 
html: "no messages", 
css: { 
"color": "red", 
"font-size":"14px" 
}}, 
options); 
return $(this).css({ 
"color": $options.css.color, 
 
}).html($options.html); 
} 
 
 
$('.ye').myPlugin({html:"So easy,yes?",css:{"color":"green","font-size":"20px"}}); 
</script> 
</body> 
</html> 
</span> 

好的,上面你也看到了一点点$.extend()的用法。 

1.合并多个对象。 

这里使用的就是$.extend()的嵌套多个对象的功能。 

所谓嵌套多个对象,有点类似于数组的合并的操作。 

但是这里是对象。举例说明。

<span style="font-size:18px;">//用法: jQuery.extend(obj1,obj2,obj3,..) 
var Css1={size: "10px",style: "oblique"} 
var Css2={size: "12px",style: "oblique",weight: "bolder"} 
$.jQuery.extend(Css1,Css2) 
//结果:Css1的size属性被覆盖,而且继承了Css2的weight属性 
// Css1 = {size: "12px",style: "oblique",weight: "bolder"} 
</span> 

2.深度嵌套对象。

<span style="font-size:18px;"> jQuery.extend( 
{ name: “John”, location: { city: “Boston” } }, 
{ last: “Resig”, location: { state: “MA” } } 
); 
// 结果: 
// => { name: “John”, last: “Resig”, location: { state: “MA” } } 
// 新的更深入的 .extend() 
jQuery.extend( true, 
{ name: “John”, location: { city: “Boston” } }, 
{ last: “Resig”, location: { state: “MA” } } 
); 
// 结果 
// => { name: “John”, last: “Resig”, 
// location: { city: “Boston”, state: “MA” } } 
</span> 

3.可以给jQuery添加静态方法。

// 使用特定模块
Layui.prototype.use = function(apps, callback, exports, from) {
    var that = this;
    var dir = config.dir = config.dir ? config.dir : getPath; // 获取路径
    var head = doc.getElementsByTagName('head')[0]; // 获取第一个header

    // 对传入的 apps 参数进行处理
    apps = function(){

        // 传入字符串时, 应转为数组 layui.use('form',...)
        if(typeof apps === 'string'){
            return [apps];
        }

        // 第一个参数为 function 时, 则自动加载所有内置模块,且执行的回调即为该 function 参数
        else if (typeof apps === 'function') {
            callback = apps;
            return ['app'];
        }
        return apps;
    }(); // 立即执行

    // 如果页面已经存在 jQuery 1.7+ 库且所定义的模块依赖 jQuery,则不加载内部 jquery 模块
    if(win.jQuery && jQuery.fn.on) {
        that.each(apps, function(index, item){

            // 找到内部 jquery, 并删除
            if(item === 'jquery'){
                apps.splice(index, 1);
            }
        });
        layui.jquery = layui.$ = jQuery; // layui 为实例对象
    }

    var item = apps[0]; // 获取 apps 数组第一位元素
    var timeout = 0; // 初始化超时时间为 0
    exports = exports || [];

    // 获取静态资源host
    config.host = config.host || (dir.match(/\/\/([\s\S]+?)\//)||['//'+ location.host +'/'])[0]

    // 加载完毕
    function onScriptLoad(e, url){
        var readyRegExp = navigator.platform === 'PLaySTATION 3' ? /^complete$/ : /^(complete|loaded)$/; // 根据平台选择正则表达式

        // 当前文件已经加载完毕
        if(e.type === 'load' || (readyRegExp.test(e.currentTarget || e.srcElement).readyState)){
            config.modules[item] = url; // 存储模块真实路径
            head.removeChild(node); // 从 head 中移除 node
            (function poll(){

                // 判断 timeout > 2500 ?
                if(++timeout > config.timeout * 1000 / 4) {

                    // 超时报错
                    return error(item + ' is not a valid module', 'error'); // 记得 return, 停止执行
                }

                // 判断当前模块状态是否为 true ,为 true 执行 onCallback, 否则轮询
                config.status[item] ? onCallback() : setTimeout(poll, 4);
            })()
        }
    }

    // 回调函数
    function onCallback(){

        // 向 exports 中推入模块
        exports.push(layui[item]); // layui 为实例对象中除了 v 属性标识版本号, 其余全为模块

        apps.length > 1
        ? that.use(apps.slice(1), callback, exports, from)
        : ( typeof callback === 'function' && function(){

            // 保证文档加载完毕再执行调用
            if(layui.jquery && typeof layui.jquery === 'function' && from !== 'define' ) {
                return layui.jquery(function (){
                    callback.apply(layui, exports);
                });
            }
            callback.apply(layui, exports);
        }());
    }

    // 如果引入了聚合板,内置的模块则不必重复加载
    if(apps.length === 0 || (layui['layui.all'] && modules[item])){
        return onCallback(), that;
    }

    // 获取加载的模块 URL
    // 如果是内置模块, 则按照 dir 参数拼接模块路径
    // 如果是扩展模块, 则判断模块路径值是否以 {/} 开头,
    // 如果路径值是 {/} 开头, 则模块路径即为后面紧跟的字符。
    // 否则, 则按照 base 参数拼接模块路径
    var url = (modules[item] ? (dir + 'modules/')
        : (/^\{\/\}/.test(that.modules[item]) ? '' : (config.base || ''))
    ) + (that.modules[item] || item) + '.js';

    url = url.replace(/^\{\/\}/, '');

    // 如果扩展模块(即:非内置模块)对象已经存在,则不必再加载
    if(!config.modules[item] && layui[item]){
        config.modules[item] = url; // 并记录起该扩展模块的 url
    }

    // 首次加载模块
    if(!config.modules[item]){
        var node = doc.createElement('script'); // 创建script

        node.async = true; // 异步
        node.charset = 'utf-8'; // 文件格式

        // 请求的文件后面添加版本号
        node.src = url + function(){

            // 是否存在版本
            var version = config.version === true
            ? (config.v || (new Date()).getTime())
            : (config.version || '');

            return version ? ('?v=' + version) : '';
        }();

        head.appendChild(node); // 挂载节点

        // 对 IE 添加监听
        if(node.attachEvent && !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera){
            node.attachEvent('onreadystatechange', function(e){
                onScriptLoad(e, url);
            });
        } else {
            node.addEventListener('load', function(e){
                onScriptLoad(e, url);
            }, false)
        }

        config.modules[item] = url;
    } else { // 非首次加载
        (function poll(){
            if(++timeout > config.timeout * 1000 / 4) {
                return error(item + ' is not a valid module', 'error');
            };

            // 已加载到模块中
            (typeof config.modules[item] === 'string' && config.status[item])
            ? onCallback()
            : setTimeout(poll, 4);
        }()); // 轮询 必须是立即执行函数
    }

    return that;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值