阻止冒泡事件
export const stopPropagation = (e) => {
e = e || window.event;
if(e.stopPropagation) { // W3C阻止冒泡方法
e.stopPropagation();
} else {
e.cancelBubble = true; // IE阻止冒泡方法
}
}
防抖函数
export const debounce = (fn, wait) => {
let timer = null;
return function() {
let context = this,
args = arguments;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(() => {
fn.apply(context, args);
}, wait);
};
}
节流函数
export const throttle = (fn, delay) => {
let curTime = Date.now();
return function() {
let context = this,
args = arguments,
nowTime = Date.now();
if (nowTime - curTime >= delay) {
curTime = Date.now();
return fn.apply(context, args);
}
};
}
数据类型判断
export const getType = (value) => {
if (value === null) {
return value + "";
}
// 判断数据是引用类型的情况
if (typeof value === "object") {
let valueClass = Object.prototype.toString.call(value),
type = valueClass.split(" ")[1].split("");
type.pop();
return type.join("").toLowerCase();
} else {
// 判断数据是基本数据类型的情况和函数的情况
return typeof value;
}
}
对象深拷贝
export const deepClone = (obj, hash = new WeakMap() => {
// 日期对象直接返回一个新的日期对象
if (obj instanceof Date){
return new Date(obj);
}
//正则对象直接返回一个新的正则对象
if (obj instanceof RegExp){
return new RegExp(obj);
}
//如果循环引用,就用 weakMap 来解决
if (hash.has(obj)){
return hash.get(obj);
}
// 获取对象所有自身属性的描述
let allDesc = Object.getOwnPropertyDescriptors(obj);
// 遍历传入参数所有键的特性
let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc)
hash.set(obj, cloneObj)
for (let key of Reflect.ownKeys(obj)) {
if(typeof obj[key] === 'object' && obj[key] !== null){
cloneObj[key] = deepClone(obj[key], hash);
} else {
cloneObj[key] = obj[key];
}
}
return cloneObj
}
以上是编程学习网小编为您介绍的“JavaScript实用工具函数开发技巧”的全面内容,想了解更多关于 vuejs 内容,请继续关注编程基础学习网。
编程基础网
本文标题为:JavaScript实用工具函数开发技巧
基础教程推荐
猜你喜欢
- Ajax bootstrap美化网页并实现页面的加载删除与查看详情 2023-01-31
- Angular获取ngIf渲染的Dom元素示例 2023-07-09
- 对于一些css样式的巧妙方法进行总结(推荐) 2024-01-08
- css实现抖音订阅按钮动画效果 2023-12-09
- 极酷的三层分离的标准滑动门导航菜单 2023-12-21
- css3+伪元素实现鼠标移入时下划线向两边展开的效果 2023-12-08
- php – html选择多项选择输入,将它们存储在mysql db中并搜索匹配项 2023-10-25
- 在vue中实现嵌套页面(iframe) 2024-03-08
- vue实现竖屏滚动公告效果 2024-01-17
- html5指南-7.geolocation结合google maps开发一个小的应用 2023-12-13
