1、并不是所有的函数都能作为构造函数
众所周知,在ES6的对象拓展中,有明确的表示过,简写的对象方法不能用作构造函数,不过很多人都有疑问,为什么同样都是函数,但是简写的对象就是不能作为构造函数呢? 在MDN上的解释:Methods cannot be constructors! They will throw a TypeError if you try to instantiate them. 大概的意思就是简写方法不能是构造函数! 如果您尝试实例化它们,它们将抛出TypeError。
根本原因是:在对象中定义方法有三种方法,它们不仅在语法上不同,而且行为也不同,所以导致了简写对象方法不能用new。
2、作为构造函数的条件有哪些呢?
1、必须有[[Construct]]
2、方法必须由FunctionCreate定义
在ES6中,ES6的每个对象都与一组定义其运行时行为的内部方法相关联,那Construct是使用new 或者super时必须要存在,但是并不是所有的方法都有Construct。
3、为什么简写的对象方法不能用作构造函数?
我将举三个例子来说明哪些方法可以用new
const obj = {
f () {
console.log('obj')
}
}
const test = {
f:function() {
console.log('test')
}
}
const demo = {
f : () => {
console.log('demo')
}
}
new test.f() //test
new obj.f() //Uncaught TypeError: obj.f is not a constructor
new demo.f() //Uncaught TypeError: demo.f is not a constructor
事实证明,只有在有方法必须由FunctionCreate定义的情况下才能用构造函数。
4、最后
前端路上,你我共勉。