zoukankan      html  css  js  c++  java
  • js插件编写常用工具函数及格式

    一、基本格式

     1 ;(function(undefined) {
     2     "use strict"
     3     var _global;
     4 
     5     var plugin = {
     6         add: function(n1,n2){ return n1 + n2; },//
     7         sub: function(n1,n2){ return n1 - n2; },//
     8         mul: function(n1,n2){ return n1 * n2; },//
     9         div: function(n1,n2){ return n1 / n2; } //
    10     }
    11 
    12     // 最后将插件对象暴露给全局对象
    13     _global = (function(){ return this || (0, eval)('this'); }());
    14 
    15     // 判断是否存在加载器  存在就使用加载器  不存在就使用全局对象
    16     if (typeof module !== "undefined" && module.exports) {
    17         module.exports = plugin;     // cmd 加载
    18     } else if (typeof define === "function" && define.amd) {
    19         define(function(){return plugin;});   // amd 加载
    20     } else {
    21         !('plugin' in _global) && (_global.plugin = plugin);  // 全局加载
    22     }
    23 }());

    二、常用工具函数

    1、对象合并

    1 function extend(o,n,override) {
    2     for(var key in n){
    3         if(n.hasOwnProperty(key) && (!o.hasOwnProperty(key) || override)){
    4             o[key]=n[key];
    5         }
    6     }
    7     return o;
    8 }
    View Code

     2、自定义模版引擎

     1 function templateEngine(html, data) {
     2     var re = /<%([^%>]+)?%>/g,
     3         reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
     4         code = 'var r=[];
    ',
     5         cursor = 0;
     6     var match;
     7     var add = function(line, js) {
     8         js ? (code += line.match(reExp) ? line + '
    ' : 'r.push(' + line + ');
    ') :
     9             (code += line != '' ? 'r.push("' + line.replace(/"/g, '\"') + '");
    ' : '');
    10         return add;
    11     }
    12     while (match = re.exec(html)) {
    13         add(html.slice(cursor, match.index))(match[1], true);
    14         cursor = match.index + match[0].length;
    15     }
    16     add(html.substr(cursor, html.length - cursor));
    17     code += 'return r.join("");';
    18     return new Function(code.replace(/[
    	
    ]/g, '')).apply(data);
    19 }
    View Code
    对内贵有志气,对外贵得人心
  • 相关阅读:
    php ajax分页的例子,在使用中
    PHP远程文件管理,可以给表格排序,遍历目录,时间排序
    背景变暗的div可拖动提示窗口,兼容IE、Firefox、Opera
    CSS简洁的左侧菜单(侧拉菜单,向右显示)
    无间断循环滚动(兼容IE、FF)
    poj 1007 求逆序数
    poj 1775 简单搜索
    面向对象之继承和组合浅谈
    在flex中导入fl包
    C99中包括的特性
  • 原文地址:https://www.cnblogs.com/worldly1013/p/8779825.html
Copyright © 2011-2022 走看看