如何通过ES6的new.target属性实现模拟抽象类中的方法调用?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1056个文字,预计阅读时间需要5分钟。
来源:Symbol作为唯一值,发现Symbol无法进行new操作,只能作为函数使用,进行了new操作就会发生类型错误:new Symbol() // error Uncaught TypeError: Symbol is not a constructor
起源
最近在使用 Symbol 来做为唯一值,发现 Symbol 无法进行 new 操作,只能当作函数使用,只要进行了new 就会发生类型错误
new Symbol() // error Uncaught TypeError: Symbol is not a constructor at new Symbol (<anonymous>) at <anonymous>:1:1
在不考虑底层实现的情况下,在代码层面是否能够实现一个函数只可以进行调用而不可以进行 new 操作呢?思考之后如下写出:
function disConstructor() { if (this !== window) { throw new TypeError(' disConstructor is not a constructor') } console.log('gogo go') } // 测试结果如下 disConstructor() // gogo go new disConstructor() // error Uncaught TypeError: disConstructor is not a constructor at new disConstructor (<anonymous>:3:15) at <anonymous>:1:1
如果使用 nodejs,window 可以切换为 global, 代码运行结果不变,因为对于个人而言没有适用场景。于是就没有继续研究下去,可是最近在从新翻阅 es6 时候发现 new.target这个属性。
本文共计1056个文字,预计阅读时间需要5分钟。
来源:Symbol作为唯一值,发现Symbol无法进行new操作,只能作为函数使用,进行了new操作就会发生类型错误:new Symbol() // error Uncaught TypeError: Symbol is not a constructor
起源
最近在使用 Symbol 来做为唯一值,发现 Symbol 无法进行 new 操作,只能当作函数使用,只要进行了new 就会发生类型错误
new Symbol() // error Uncaught TypeError: Symbol is not a constructor at new Symbol (<anonymous>) at <anonymous>:1:1
在不考虑底层实现的情况下,在代码层面是否能够实现一个函数只可以进行调用而不可以进行 new 操作呢?思考之后如下写出:
function disConstructor() { if (this !== window) { throw new TypeError(' disConstructor is not a constructor') } console.log('gogo go') } // 测试结果如下 disConstructor() // gogo go new disConstructor() // error Uncaught TypeError: disConstructor is not a constructor at new disConstructor (<anonymous>:3:15) at <anonymous>:1:1
如果使用 nodejs,window 可以切换为 global, 代码运行结果不变,因为对于个人而言没有适用场景。于是就没有继续研究下去,可是最近在从新翻阅 es6 时候发现 new.target这个属性。

