Class类的介绍
类作为ES6才有的概念
类的数据类型是函数,类本身就是构造函数
每一个类都有constructor
方法,而constructor
方法在类进行实例化的时候会自调用,默认返回实例化对象,在这里定义的方法都是定义在实例对象上,
在类内部定义方法不需要function
关键字,不然会报错,直接写函数就行了,并且定义是定义在原型对象上
class Student {
constructor(x, y) {
this.x = x;
this.y = y; // 定义在实例原型对象
/*
一般都是返回的都是实例化对象,但是可以指定返回结果,和ES5中的构造函数一样,如果返回的是基本类型值没有影响,如果返回的是引用类型值,则返回的引用类型值会替代实例化对象
*/
}
// 定义在原型对象
getX() {
}
getY() {
}
}
Class类就介绍到这里,现在开始讲解用Class类写轮播图
// 开启严格模式,(推荐大家写代码的时候也使用严格模式,这样可以大大的提高代码的质量)
'use strict';
class Banner {
constructor(box, list, smallLi, aLi, liWidth, time) {
this.list = list; // 移动的ul
this.smallLi = smallLi; // 小点
this.liWidth = liWidth; // 每次移动的距离,等同于每张图片的宽
this.index = 1; // 索引 因为是无缝滚动轮播,所以第一张前面还有一张,所以第一张的索引为1
this.aLi = aLi; // 轮播的图片li元素,如果要有上传图片的功能,则就是img元素,通过修改src属性更换图片
this.length = aLi.length; // 轮播图片的数量
this.flag = false; // 开关 防止多次切换
this.box = box; // 最外层的盒子
this.time = time; // 轮播自动切换的时间
this.init(); // 在实例化时自调用
}
getStyle(ele, attr) {
if (!!ele.currentStyle) {
return ele.currentStyle[attr];
} else {
return getComputedStyle(ele, null)[attr];
}
}
animate(ele, json, callback) {
self = this;
clearInterval(ele.time);
ele.time = setInterval(function () {
let flag = false;
for (let attr in json) {
let current = null;
if (attr == 'opacity') {
current = parseInt((self.getStyle(ele, attr))) * 100;
} else if (attr == 'zIndex') {
ele.style[attr] = json[attr];
} else {
current = parseInt((self.getStyle(ele, attr)));
}
let step = (json[attr] - current) / 6;
step = step < 0 ? Math.floor(step) : Math.ceil(step);
let result = step + current;
if (attr == 'opacity') {
ele.style[attr] = result / 100;
} else {
ele.style[attr] = result + 'px';
}
if (result != json[attr]) {
flag = true;
}
if (!flag) {
clearInterval(ele.time);
if (typeof callback == 'function') {
callback();
}
}
}
}, 30);
}
// getStyle和animate方法在之前就已经讲解过了,大家可以看我之前的文章
// 下一张切换函数
next() {
// 定义_this存储this,作为缓冲
let _this = this;
if (!this.flag)