JavaScript is an object-based language. JavaScript 是一个基于对象的语言. But it's not a real OOP language. 但它并不是真正面向对象的语言.

说明:

三种特性

理解

案例

tab

ES5 版本

;(function() {
  var Tab = function(mode) {
    this.mode = (mode === 'fade' || mode === 'slide') ? mode : 'fade';
    this.oTab = $('.J_tab');
    this.oPage = $('.J_page');
    this.oPageItems = this.oPage.find('.item');
    this.oPageWrap = this.oPage.children('.page-wrap');
    this.init();
  }

  Tab.prototype.init = function() {
    this.setMode();
    this.bindEvent();
  }

  Tab.prototype.setMode = function() {
    this.oPageWrap.addClass(this.mode);
  }

  Tab.prototype.bindEvent = function() {
    this.oTab.on('click', '.item', $.proxy(this.tabClick, this));
  }

  Tab.prototype.tabClick = function(e) {
    var e = e || window.event,
        tar = e.target || e.srcElement,
        curIdx = $(tar).index();

    if (tar.className === 'item') {
      $(tar).addClass('current').siblings('.item').removeClass('current');
      this._pageChange(curIdx);
    }
  }

  Tab.prototype._pageChange = function(index) {
    switch (this.mode) {
      case 'fade':
        this._fadePage(index);
        break;
      case 'slide':
        this._slidePage(index);
        break;
      default:
        this._slidePage(index);
        break;
    }
  }

  Tab.prototype._fadePage = function(index) {
      this.oPageItems.eq(index).fadeIn(100).siblings('.item').fadeOut(100);
  }

  Tab.prototype._slidePage = function(index) {
    this.oPageWrap.animate({
      left: (-index * 500) + 'px'
    });
  }

  var tab = new Tab('slide');
})();

ES6 版本

export default class Tab {
  constructor(mode) {
    this.mode = (mode === 'fade' || mode === 'slide') ? mode : 'fade';
    this.oTab = $('.J_tab');
    this.oPage = $('.J_page');
    this.oPageItems = this.oPage.find('.item');
    this.oPageWrap = this.oPage.children('.page-wrap');
    this.init();
  }
  init() {
    this.setMode();
    this.bindEvent();
  }

  setMode() {
    this.oPageWrap.addClass(this.mode);
  }

  bindEvent() {
    this.oTab.on('click', '.item', $.proxy(this.tabClick, this));
  }

  tabClick(e) {
    var e = e || window.event,
        tar = e.target || e.srcElement,
        curIdx = $(tar).index();

    if (tar.className === 'item') {
      $(tar).addClass('current').siblings('.item').removeClass('current');
      this._pageChange(curIdx);
    }
  }

  _pageChange(index) {
    switch (this.mode) {
      case 'fade':
        this._fadePage(index);
        break;
      case 'slide':
        this._slidePage(index);
        break;
      default:
        this._slidePage(index);
        break;
    }
  }

  _fadePage(index) {
      this.oPageItems.eq(index).fadeIn(100).siblings('.item').fadeOut(100);
  }

  _slidePage(index) {
    this.oPageWrap.animate({
      left: (-index * 500) + 'px'
    });
  }
}

继承