jQuery插件写法小结之重写轮播图功能

本文总结了jQuery插件的编写技巧,包括处理复杂参数列表、统一命名空间、允许访问默认设置、保持链式调用以及利用Array.prototype.slice.call()方法。通过实例展示了如何重写轮播图功能,提供更优雅的API和更好的可定制性。
摘要由CSDN通过智能技术生成

最近在维护老网站的时候,发现一些jQuery库的使用有些臃肿,并且大部分自定义的js文件很容易污染全局变量,所以想着重写下,虽然jQuery的辉煌时代已经过去了,但是他的思想,依旧灿烂(滚去维护去)

在这里插入图片描述

先举个栗子

;(function($) {
   
  var methods = {
   
    init: function(options) {
   
      // 可自定义扩展项
      options = $.extend(
        true,
        {
   }, 
        $.fn.myPlugin.defaults,
        options
      );
      console.log('options', options, this)
  
      return this;
    },
    getName: function() {
   
      console.log('Name is ', $.fn.myPlugin.defaults.name, '.')
    },
    getAge: function() {
   
      console.log('Age is ', $.fn.myPlugin.defaults.age, '.')
    },
    show: function(){
   
      return this.each(function(){
   
        this.style.display == "none" && (this.style.display = '')
        if (getComputedStyle(this, '').getPropertyValue("display") == "none")
          this.style.display = defaultDisplay(this.nodeName)
      })
    },
    hide: function() {
   
      return this.css("display", "none")
    }
  };

  // 命名空间最好只有一个
  $.fn.myPlugin = function(method) {
   

    // 方法调用,可满足三种情况:1. method, 2. init, 3. error
    if(methods[method]) {
   
      return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));  //将具有length属性的对象转成数组
    } else if(typeof method === 'object' || !method) {
   
      // 如果没有参数或者参数
      return methods.init.apply(this, arguments);
    } else 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值