[英]What is the difference between these object literals?
I created two Objects.我创建了两个对象。 The first one is working as intended.
第一个正在按预期工作。
let working = {constructor: function(){
console.log("working");
}};
let notworking = {constructor(){
console.log("notworking");
}}
new working.constructor();
new notworking.constructor();
But the second one throws an Error.但是第二个抛出错误。 The Error message is:
错误信息是:
Uncaught TypeError: notworking.constructor is not a constructor
Tested on Firefox and Chrome.在 Firefox 和 Chrome 上测试。
In Firefox DevTools the Object itself looks the same.在 Firefox DevTools 中,对象本身看起来是一样的。 There is a difference in the constructor method.
构造函数方法有所不同。 The working constructor has properties arguments, caller, length and name.
工作构造函数具有属性参数、调用者、长度和名称。 The notworking constructor has only the properties length and name.
notworking 构造函数只有属性长度和名称。
So what is the difference between these two objects or constructors?那么这两个对象或者构造函数有什么区别呢?
The second syntax is the method syntax and it was introduced in ECMAScript 2015. They are almost equivalent, but there's a difference.第二种语法是方法语法,它是在 ECMAScript 2015 中引入的。它们几乎是等效的,但有区别。 In the first object,
constructor
is just a key whose value is a function.在第一个对象中,
constructor
只是一个键,它的值是一个函数。 In the second object, constructor
is a method .在第二个对象中,
constructor
是一个方法。 Method definitions are not constructable方法定义不可构建
Methods cannot be constructors.
方法不能是构造函数。 They will throw a TypeError if you try to instantiate them
如果您尝试实例化它们,它们将抛出 TypeError
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.