无法将ES6类构造函数称为普通函数的原因是什么? [英] What is the reason ES6 class constructors can't be called as normal functions?

查看:157
本文介绍了无法将ES6类构造函数称为普通函数的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6类的构造函数不能称为普通函数.根据ES6,完成此操作后应提高TypeError.我曾经以为,类只是原型中构造函数或函数的语法糖,但事实并非如此.

ES6 class constructors can't be called as normal functions. According to ES6 a TypeError should be raised when this is done. I used to think that classes were just syntactic sugar for a constructor function + functions in the prototype, but this makes it slightly not so.

我想知道,这背后的原理是什么?除非我错过了什么,否则它会阻止使用自定义this调用该函数,这对于某些模式可能是理想的.

I'm wondering, what was the rationale behind this? Unless I missed something, it prevents calling the function with a custom this, which could be desirable for some patterns.

推荐答案

这背后的原理是什么?

what was the rationale behind this?

这是一种保障措施.当您在没有new的情况下调用ES5 function构造函数时,它做了非常令人讨厌的事情,无声地失败了.引发异常可以帮助您发现错误.

It's a safeguard. When you called an ES5 function constructor without new, it did very undesirable things, failing silently. Throwing an exception helps you to notice the mistake.

当然,他们本可以选择调用语法与构造相同,但是强制使用new关键字是一件好事,有助于我们轻松识别实例.

Of course they could have opted for the call syntax to just work the same as construction, but enforcing the new keyword is a good thing that helps us to easily recognise instantiations.

它防止使用自定义this调用该函数,这对于某些模式可能是理想的.

It prevents calling the function with a custom this, which could be desirable for some patterns.

是的,这是ES6中的根本变化. this值由超类初始化,它允许带有内部插槽的子类内置对象-有关详细信息,请参见此处.这与传递自定义此参数冲突,并且为了保持一致,绝对不能允许这样做.

Yes, this is what fundamentally changed in ES6. The this value is initialised by the superclass, which allows subclass builtins with internal slots - see here for details. This conflicts with passing a custom this argument, and for consistency one must never allow that.

这篇关于无法将ES6类构造函数称为普通函数的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆