JavaScript常见封装方法


1.最简单的,使用变量,然后用匿名函数包裹,不封装

2.对象字面量简单封装(不完整的模块模式,因为无法达到变量、方法私有效果。不过确实有分离和组织代码的能力,也就算一种简略的模块模式的实现方式)

var Carousel = {
	init: function(){...},
	bind: function(){...},
	showPre: function(){...},
	showNext: function(){...}
};

3.原型构造器模式封装

function Carousel(){
	this.init();
}

Carousel.prototype = {
	init: function(){...},
	bind: function(){...},
	showPre: function(){...},
	showNext: function(){...}
};

4.模块模式与原型构造器模式绑定多个:使用一个数组保存实例

var CarouselCenter = (function () {
  var carouselList = [];

  function init($carousel) {
    $carousel.each(function () {
      var $cal = $(this);
      if ($cal.hasClass('init')) {
        return;
      }
      carouselList.push(new Carousel($cal));
      $cal.addClass('init');
    });
  }

  function getList() {
    return carouselList;
  }

  function Carousel($carousel) {}

  Carousel.prototype = {
    bind: function () {
      var _this = this;
      this.$pre.on('click', function () {
        _this.showPre();
      });
      this.$next.on('click', function () {
        _this.showNext();
      });
    },

    showPre: function () {
      this.$ct.prepend(this.$ct.children().last());
      this.$ct.css('left', 0 - this.imgWidth);
      this.$ct.animate({ left: 0 });
    },

    showNext: function () {
      var $ct = this.$ct;
      $ct.animate({ left: 0 - this.imgWidth }, function () {
        $ct.append($ct.children().first());
        $ct.css('left', 0);
      });
    },
  };

  return {
    init: init,
    getList: getList,
  };
})();

// 调用
// CarouselCenter.init($('#c1'))
// CarouselCenter.init($('#c2'))
// CarouselCenter.init($('#c2')) //不会重复绑定

// CarouselCenter.init($('.carousel'))

5.通用写法

(function (window, $) {
  function Carousel() {}

  Carousel.prototype = {};

  window.Carousel = Carousel;
})(window, jQuery);

ps:

模式目的:编写易于维护的代码,其中一个最重要方面是能够找到代码中重复出现的主题并优化它们。


文章作者: Angus
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Angus !
  目录