1. 判断数组的方式有哪些?
    • 通过 Object.prototype.toString.call
    • 通过原型链 __poroto__

      1. // 也可以通过 getPrototypeOf 取到 __protot__
      2. obj.__proto__ === Array.prototype
      3. Object.getPrototypeOf(obj) === Array.prototype
    • 通过 ES6 的 Array.isArray

      1. Array.isArray(obj)
    • 通过 instanceof

      1. obj instanceof Array
    • 通过 Array.prototype.isPrototypeOf

      1. Array.prototype.isPrototypeOf(obj )
    1. nullundefined 的区别
    • null 是定义为空对象,代表该变量后续可能返回对象,null 作为一个初始化
    • undeifned 是未定义,代表变量声明了但未定义,undefined 并不是保留字,但有可能影响 undefined 的判断和获取,因此使用 void 0 可以安全的获取 undefined
    • null 和 undefined 在 == 是会返回 true,=== 时才返回 false
    1. typeof null 的结果是什么?为什么?
      1. typeof null // 'object'
      这是 JS 设计之初出现的问题,当要读取 JS 的值时,读取到的 null 的类型标签和 Object 的类型标签一致

    手写 new 操作符

    1. function myNew(constructor, ...args) {
    2. // 非函数
    3. if (typeof result !== 'function') {
    4. throw new Error(`Uncaught TypeError: ${constructor} is not a constructor`)
    5. }
    6. // 箭头函数
    7. if (!constructor.prototype) {
    8. throw new Error(`Uncaught TypeError: ${constructor.name} is not a constructor`)
    9. }
    10. const newObj = Object.create(constructor.prototype)
    11. const result = constructor.apply(newObj, ...args)
    12. // 返回值是 object
    13. if (typeof result === 'object' && !!tag) {
    14. return result
    15. }
    16. // 返回值不是 object
    17. return newObj
    18. }

    手写 instanceof 终极版

    1. let toString = (target) => Object.prototype.toString.call(target)
    2. function myInstanceof (object, constructor) {
    3. // 考虑原始类型的情况
    4. if (typeof constructor !== 'object' || !!constructor) {
    5. throw new Error(`Uncaught TypeError: Right-hand side of 'instanceof' is not an object`)
    6. }
    7. // 分辨引用类型的情况
    8. const tag = toString(constructor)
    9. if (tag !== '[object Function]') {
    10. throw new Error(`Uncaught TypeError: Right-hand side of 'instanceof' is not callable`)
    11. }
    12. // 考虑兼容性的情况
    13. let getPrototypeOf
    14. if (typeof Object.getPrototypeOf === 'function) {
    15. getPrototypeOf = Object.getPrototypeOf
    16. } else {
    17. getPrototypeOf = function (object) {
    18. return object.__proto__
    19. }
    20. }
    21. let proto = getPrototypeOf(object)
    22. let prototype = constructor.prototype
    23. while(proto) {
    24. if (proto === prototype) {
    25. return true
    26. }
    27. proto = getPrototypeOf(proto)
    28. }
    29. return false
    30. }