- instanceof实现判断简单类型
class PrimitiveString { static [Symbol.hasInstance](x) { return typeof x === 'string' }}console.log('hello' instanceof PrimitiveString)
- 原型链
链接实例和原型,实现继承。 - 闭包
外部函数内包裹内部函数,内部函数可以访问外部函数变量,并且外部函数上下文环境不会销毁。 - 手写promise
const PENDING = 'pending'const RESOLVED = 'resolved'const REJECTED = 'rejected'function MyPromise(fn) { const that = this that.state = PENDING that.value = null that.resolvedCallbacks = [] that.rejectedCallbacks = [] // 待完善 resolve 和 reject 函数 // 待完善执行 fn 函数 function resolve(value) { if (that.state === PENDING) { that.state = RESOLVED that.value = value that.resolvedCallbacks.map(cb => cb(that.value)) }}function reject(value) { if (that.state === PENDING) { that.state = REJECTED that.value = value that.rejectedCallbacks.map(cb => cb(that.value)) }}try { fn(resolve, reject)} catch (e) { that.reject(e)}}MyPromise.prototype.then = function(onFulfilled, onRejected) { const that = this onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r } if (that.state === PENDING) { that.resolvedCallbacks.push(onFulfilled) that.rejectedCallbacks.push(onRejected) } if (that.state === RESOLVED) { onFulfilled(that.value) } if (that.state === REJECTED) { onRejected(that.value) }}
- 手写call
Function.prototype.myCall = function(context) { if (typeof this !== 'function') { throw new TypeError('Error') } context = context || window context.fn = this const args = [...arguments].slice(1) const result = context.fn(...args) delete context.fn return result}
- v8垃圾回收机制
- 16进制 <=> rgb
function hexToRGB(hex){ var hex = hex.replace("#","0x"), r = hex >> 16, g = hex >> 8 & 0xff, b = hex & 0xff; return "rgb("+r+","+g+","+b+")";}function RGBToHex(rgb){ var rgbArr = rgb.split(/[^\d]+/), color = rgbArr[1]<<16 | rgbArr[2]<<8 | rgbArr[3]; return "#"+color.toString(16);}