1. instanceof实现判断简单类型
    1. class PrimitiveString {
    2. static [Symbol.hasInstance](x) {
    3. return typeof x === 'string'
    4. }
    5. }
    6. console.log('hello' instanceof PrimitiveString)
    1. 原型链
      链接实例和原型,实现继承。
    2. 闭包
      外部函数内包裹内部函数,内部函数可以访问外部函数变量,并且外部函数上下文环境不会销毁。
    3. 手写promise
    1. const PENDING = 'pending'
    2. const RESOLVED = 'resolved'
    3. const REJECTED = 'rejected'
    4. function MyPromise(fn) {
    5. const that = this
    6. that.state = PENDING
    7. that.value = null
    8. that.resolvedCallbacks = []
    9. that.rejectedCallbacks = []
    10. // 待完善 resolve 和 reject 函数
    11. // 待完善执行 fn 函数
    12. function resolve(value) {
    13. if (that.state === PENDING) {
    14. that.state = RESOLVED
    15. that.value = value
    16. that.resolvedCallbacks.map(cb => cb(that.value))
    17. }
    18. }
    19. function reject(value) {
    20. if (that.state === PENDING) {
    21. that.state = REJECTED
    22. that.value = value
    23. that.rejectedCallbacks.map(cb => cb(that.value))
    24. }
    25. }
    26. try {
    27. fn(resolve, reject)
    28. } catch (e) {
    29. that.reject(e)
    30. }
    31. }
    32. MyPromise.prototype.then = function(onFulfilled, onRejected) {
    33. const that = this
    34. onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
    35. onRejected =
    36. typeof onRejected === 'function'
    37. ? onRejected
    38. : r => {
    39. throw r
    40. }
    41. if (that.state === PENDING) {
    42. that.resolvedCallbacks.push(onFulfilled)
    43. that.rejectedCallbacks.push(onRejected)
    44. }
    45. if (that.state === RESOLVED) {
    46. onFulfilled(that.value)
    47. }
    48. if (that.state === REJECTED) {
    49. onRejected(that.value)
    50. }
    51. }
    1. 手写call
    1. Function.prototype.myCall = function(context) {
    2. if (typeof this !== 'function') {
    3. throw new TypeError('Error')
    4. }
    5. context = context || window
    6. context.fn = this
    7. const args = [...arguments].slice(1)
    8. const result = context.fn(...args)
    9. delete context.fn
    10. return result
    11. }
    1. v8垃圾回收机制
    2. 16进制 <=> rgb
    1. function hexToRGB(hex){
    2. var hex = hex.replace("#","0x"),
    3. r = hex >> 16,
    4. g = hex >> 8 & 0xff,
    5. b = hex & 0xff;
    6. return "rgb("+r+","+g+","+b+")";
    7. }
    8. function RGBToHex(rgb){
    9. var rgbArr = rgb.split(/[^\d]+/),
    10. color = rgbArr[1]<<16 | rgbArr[2]<<8 | rgbArr[3];
    11. return "#"+color.toString(16);
    12. }