导航
JavaScript is an object-based language. JavaScript 是一个基于对象的语言. But it's not a real OOP language. 但它并不是真正面向对象的语言.
说明:
;(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');
})();
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'
});
}
}
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHi() {
console.log(`I'm ${this.name}`);
}
}
class Student extends Person {
constructor(name, age, school) {
super(name, age);
this.school = school;
}
run() {
console.log('run');
}
}
var stu = new Student('Lance', 26, 'School');
console.log(stu);
通过封装,控制类的属性与方法的可访问方式
然而 ES6 没有支持面向对象的封装特性
const doAjax = Symbol('doAjax');
class HTTP {
[doAjax](options) {
...
}
}
const http = new HTTP();
console.log(http);
实例化后,无法访问 doAjax 方法,从而实现方法私有化