这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战
-
事件代理(委托)是什么?
- 委托父级代为执行事件;利用事件冒泡,只指定一个事件处理程序,就可以管理某一类型的所有事件;如:如果在 ul 中有100个 li 需要添加事件处理程序,可以根据 for 来进行遍历,但是也可以根据父级的 ul 来进行添加。在性能的角度来看,把 ul 建立事件会减少 dom 的交互次数,提高性能;
-
手写字符串 trim 方法,保证浏览器兼容性
String.prototype.trim = function () { return this.replace(/^\s+/, '').replace(/\s+$/, '') } -
如何获取多个数字中的最大值
// 方法一 function max() { const nums = Array.prototype.slice.call(arguments) // 变为数组 let max = 0 nums.forEach(n => { if (n > max) { max = n } }) return max } // 方法二 Math.max(10, 20, 30, 40) -
如何用 JS 实现继承?
-
class 继承
class Point { constructor(x, y) { this.x = x this.y = y } } class ColorPoint extends Point { constructor(x, y, color) { this.color = color // ReferenceError super(x, y) this.color = color // 正确 } } -
prototype 继承
function Father() { this.property = true } Father.prototype.getFatherValue = function() { return this.property } function Son() { this.sonProperty = false } // 继承 Father Son.prototype = new Father() // Son.prototype被重写,导致Son.prototype.constructor也一同被重写 Son.prototype.getSonVaule = function() { return this.sonProperty } var instance = new Son() alert(instance.getFatherValue()) // true
-
-
如何捕获 JS 程序中的异常?
- try...catch
- 能捕获到代码执行的错误
- 捕获不到语法的错误
- 无法处理异步中的错误
- 影响代码可读性
- window.onerror
- 能捕获到运行时错误
- 用来捕获预料之外的错误
- 监听不到资源加载的报错,事件处理函数只能声明一次,不会重复执行多个回调
- window.addEventListener('error')
- 可以监听到资源加载报错,也可以注册多个事件处理函数
- 无法判断 HTTP 的状态是 404 还是其他;需要配合服务端日志进行排查分析才可以
- window.addEventListener('unhandledrejection')
- 捕获 Promise 错误,当 Promise 被 reject 且没有 reject 处理器的时候触发
- try...catch
-
什么是 JSON ?
json是一种数据格式,本质是一段字符串json格式和 JS 对象结构一致,对 JS 语言更友好window.JSON是一个全局对象:JSON.stringifyJSON.parse
-
获取当前页面 url 参数
-
传统方式:查找
location.searchfunction query(name) { const search = location.search.substr(1) // 去掉问号 const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i') const res = search.match(reg) if (res === null) { return null } return res[2] } -
新 API:
URLSearchParamsfunction query(name) { const search = location.search const p = new URLSearchParams(search) return p.get(name) }
-