const Util = {
//判断是否是Object 类型
isObject(o) {
//typeof 等于object的也可能是null, 所以要加上 o !== null ; 后面两个条件是防止 new Date()等类型的object, 要判断它的构造函数
return typeof o === 'object' && o !== null && o.constructor && o.constructor === Object;
},
// "...args"是扩展运算符, 把函数传过来的参数全部析构赋值给args, args的个数没有限制,参考[http://es6.ruanyifeng.com/?search=set&x=6&y=9#docs/array]
extend(...args) {
//获得参数第一个, 第一个是构造环境的this
const to = Object(args[0]);
//循环args(此时是一个数组),从第二个开始
for (let i = 1; i < args.length; i += 1) {
const nextSource = args[i];
//存在则继续
if (nextSource !== undefined && nextSource !== null) {
//Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组,
//数组中属性名的排列顺序和使用 for...in 循环遍历该对象时返回的顺序一致 。
const keysArray = Object.keys(Object(nextSource));
for (let nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex += 1) {
//传过来的object中的属性
const nextKey = keysArray[nextIndex];
//Object.getOwnPropertyDescriptor() 方法返回指定对象上一个自有属性对应的属性描述符。
//(自有属性指的是直接赋予该对象的属性,不需要从原型链上进行查找的属性)
const desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
//desc 存在并且可枚举
if (desc !== undefined && desc.enumerable) {
//this.xxx 和 nextSource.xxx(参数的属性)都是Object
if (Utils.isObject(to[nextKey]) && Utils.isObject(nextSource[nextKey])) {
// 迭代extend 函数
Utils.extend(to[nextKey], nextSource[nextKey]);
}
//this.xxx 不是Object
else if (!Utils.isObject(to[nextKey]) && Utils.isObject(nextSource[nextKey])) {
//把this.xxx置为空对象
to[nextKey] = {};
// 迭代extend 函数
Utils.extend(to[nextKey], nextSource[nextKey]);
} else {
// 直接继承
to[nextKey] = nextSource[nextKey];
}
}
}
}
}
return to;
}
export default Util;
使用方法:
const swiper = this;
Utils.extend(swiper, {
autoplay: {
running: false,
paused: false,
run: Autoplay.run.bind(swiper),
start: Autoplay.start.bind(swiper),
stop: Autoplay.stop.bind(swiper),
pause: Autoplay.pause.bind(swiper),
onTransitionEnd(e) {
if (!swiper || swiper.destroyed || !swiper.$wrapperEl) return;
if (e.target !== this) return;
swiper.$wrapperEl[0].removeEventListener('transitionend', swiper.autoplay.onTransitionEnd);
swiper.$wrapperEl[0].removeEventListener('webkitTransitionEnd', swiper.autoplay.onTransitionEnd);
swiper.autoplay.paused = false;
if (!swiper.autoplay.running) {
swiper.autoplay.stop();
} else {
swiper.autoplay.run();
}
},
},
});
extend进行到autoplay, 是一个对象, 则循环判断autoplay里面的属性, 发现running等状态等不是一个Object, 则直接继续继承;