React · 8/84
1. 为什么推荐将静态资源放到 CDN 上 2. Class 组件的局限性 3. Class 组件与函数组件 4. Composition API 与 Hooks 对比 5. Vue 中 computed 和 watch 的区别 6. 爬楼梯问题 7. createElement 执行过程 8. 限制构造函数只能通过 new 调用 9. 判断 React 组件类型 10. 受控与非受控组件 11. 自定义 Hook 开发 12. 什么是 DNS 劫持? 13. 判断对象是否是 React 元素 14. HOC 与 Render Props 15. React 中 Element、Component、Node、Instance 的区别 16. Hooks 使用规则 17. HTTP/2 多路复用原理 18. HTTP 报文结构 19. HTTPS 握手过程 20. Immutable 在 React 中的应用 21. 实现图片懒加载 22. JavaScript == 运算符的机制 23. JavaScript 数组的内存存储方式 24. JSX 本质 25. Immutable 在 React 中的应用 26. 最大子序和 27. React Router 的 Link 和 a 标签的区别 28. JSX语法糖本质 29. 父组件调用子组件方法 30. 移动端样式适配方案 31. Portal 中的事件冒泡机制 32. React 17 新特性 33. React 18 新特性与并发渲染 34. React 组件渲染流程 35. React 是什么 36. React元素$$typeof属性 37. React 组件通信方式 38. React 错误边界处理 39. React 核心概念 40. React 组件设计 41. React Fiber 架构 42. React Hooks 原理与规则 43. React 常用 Hooks 使用指南 44. React.memo 和 memoize 函数的区别 45. React 生命周期演变 46. React 性能优化实践 47. React 性能优化策略 48. React Portals 的使用场景 49. React 中的 ref 使用 50. React 和 React-DOM 的关系 51. React 为什么不直接使用 requestIdleCallback 52. React-Router 原理与工作方式 53. React 合成事件机制 54. React 服务端渲染实现 55. React 事务机制 56. setState 同步异步问题 57. setTimeout 为什么不能保证及时执行 58. Redux 工作流与中间件 59. React 服务端渲染实现 60. 单页应用如何提高加载速度 61. Source Map 的工作原理 62. TypeScript 中的命名空间与模块 63. Taro 多端框架实现原理 64. Taro 2.x 和 Taro 3 的区别 65. TypeScript 与 JavaScript 的区别 66. TCP 三次握手和四次挥手 67. useEffect 支持 async/await 68. useEffect 闭包陷阱 69. useMemo 和 useCallback 的使用场景 70. useContext 的使用方法 71. useReducer 与 Redux 对比 72. useState 连续调用 setState 导致值丢失 73. 实现 useTimeout Hook 74. useRef、ref 和 forwardRef 的区别 75. 虚拟DOM性能分析 76. 实现 useUpdate 强制组件重新渲染 77. Virtual DOM 的意义 78. 虚拟DOM的三个组成部分 79. Virtual DOM 与 Diff 算法 80. Vue 页面渲染流程 81. Vue 与 React 对比 82. Vue 与 React 的 Diff 算法差异 83. Vue2 数组变化检测的限制与解决方案 84. Vue3 实现 Modal 组件

限制构造函数只能通过 new 调用

三种方法确保构造函数必须使用 new 调用,避免普通函数调用

问题

JavaScript 中的函数可以作为构造函数使用(new Func())或作为普通函数调用(Func()),但语言本身不会区分这两种调用方式。如何限制构造函数只能通过 new 调用?

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

// 使用 new 调用
console.log(new Person("战场", "小包")); // Person {firstName: "战场", lastName: "小包"}

// 普通函数调用 - 不会报错,但行为异常
console.log(Person("战场", "小包")); // undefined

解答

方案一:使用 instanceof

利用 new 调用时 this 指向实例,普通调用时 this 指向 window(非严格模式)或 undefined(严格模式)的特性:

function Person(firstName, lastName) {
    if (!(this instanceof Person)) {
        throw new TypeError('Function constructor Person cannot be invoked without "new"');
    }
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = this.firstName + this.lastName;
}

// 普通调用会抛出错误
console.log(Person("战场", "小包")); 
// Uncaught TypeError: Function constructor Person cannot be invoked without "new"

// new 调用正常
console.log(new Person("战场", "小包")); // Person {...}

这种方案存在瑕疵,可以通过 call/apply 伪造实例绕过检测:

console.log(Person.call(new Person(), "战场", "小包")); // 可以执行

方案二:使用 new.target(推荐)

ES6 引入的 new.target 属性专门用于检测函数是否通过 new 调用:

function Person(firstName, lastName) {
    if (!new.target) {
        throw new TypeError('Function constructor Person cannot be invoked without "new"');
    }
    this.firstName = firstName;
    this.lastName = lastName;
}

// 普通调用返回 undefined
console.log("not new:", Person("战场", "小包")); 
// Uncaught TypeError: Function constructor Person cannot be invoked without "new"

// new 调用返回构造函数
console.log("new:", new Person("战场", "小包")); // Person {...}

方案三:使用 ES6 Class(最佳方案)

Class 语法天然限制必须使用 new 调用:

class Person {
    constructor(name) {
        this.name = name;
    }
}

// 普通调用直接报错
Person("小包"); 
// Uncaught TypeError: Class constructor Person cannot be invoked without 'new'

// 必须使用 new
new Person("小包"); // Person {name: "小包"}

扩展:使用 new.target 实现抽象类

在继承场景中,new.target 返回实际调用的构造函数(父类或子类),可以实现抽象类:

class Animal {
    constructor(type, name, age) {
        // 禁止直接实例化 Animal
        if (new.target === Animal) {
            throw new TypeError("Abstract class Animal cannot be instantiated");
        }
        this.type = type;
        this.name = name;
        this.age = age;
    }
}

class Dog extends Animal {
    constructor(name, age) {
        super("dog", name, age);
    }
}

// 抽象类不能实例化
new Animal("dog", "baobao", 18); 
// Uncaught TypeError: Abstract class Animal cannot be instantiated

// 子类可以正常实例化
new Dog("baobao", 18); // Dog {type: "dog", name: "baobao", age: 18}

关键点

  • instanceof 方案利用 this 指向差异,但可被 call/apply 绕过,适用于低版本浏览器
  • new.target 是 ES6 专门为检测构造函数调用方式设计的属性,返回 new 作用的构造函数或 undefined
  • ES6 Class 天然限制必须使用 new 调用,是面向对象编程的最佳方案
  • new.target 在继承中返回子类构造函数,可用于实现抽象类(父类不可实例化,只能通过子类使用)