这里只列举了几个常用的
-
最优化的继承方式: 圣杯模式
var inherit = (function(c, p) { var F = function(){}; return function(c,p) { F.prototype = p.prototype; c.prototype = new F(); c.uber = p.prototype; c.prototype.constructor = c; } })();
-
类型判断
基本类型(null) 使用String(null) 返回’null’
基本类型(string/number/boolean/undefined) 以及 function 使用typeof
其余引用类型(Array/Date/RegExp/Error/Object) 调用toString后根据[object xxx]进行判断var class2Type = {} 'Array Date RegExp Object Error'.split(' ').forEach(e => class2Type['[object ' + e + ']'] = e.toLowerCase()) function type(obj) { if(obj == null) return String(obj) return typeof obj === 'object' ? class2Type[Object.prototype.toString.call(obj)] || 'object' : typeof obj }
-
防抖和节流
防抖:将多次高频操作优化为只在最后一次执行
function debounce(fn, wait, immediate) {
let timer = null
return function() {
let args = arguments
let context = this
// 初始立即执行
if (immediate && !timer) {
fn.apply(context, args)
}
if(timer) clearTimeout(timer)
timer = setTimeout(function() {
fn.apply(context, args)
}, wait)
}
}
节流:每隔一段时间执行一次
function throttle(fn, wait, immediate) {
let timer = null
let callNow = immediate
return function() {
let context = this,
args = arguments
// 是否立即执行
if (callNow) {
fn.apply(context, args)
callNow = false
}
// 每隔一段时间执行
if (!timer) {
timer = setTimeout(function() {
fn.apply(context, args)
timer = null
}, wait)
}
}
}
- 函数柯里化
在一个函数中,首先填充几个函数,然后再返回一个新的函数的技术,称为函数的柯里化。
通常用于在不侵入函数的前提下,为函数 预置通用函数, 供多次重复使用。
const add = function add(x) {
return function(y) {
return x + y
}
}
// 通用初始函数
const add1 = add(1)
add1(2) === 3
add1(20) === 21