简体   繁体   English

这些对象字面量有什么区别?

[英]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

From: MDN来自: MDN

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript 中的对象、Object 文字和模板文字有什么区别 - What is the difference between Objects, Object Literals and Template Literals in JavaScript 模板文字中的换行符和字符串文字中的'\\'之间有什么区别? - What's the difference between line breaks in template literals and '\' in string literals? 对象文字和返回IIFE内部对象的函数之间的区别和好处/缺点是什么? - What is the difference and benefits/drawbacks between object literals and functions that return an object inside an IIFE? JavaScript的对象文字与控制台记录时似乎命名的对象有什么区别? - What is the difference between JavaScript's object literals and object that appears to be named when console logged? 声明为对象文字和函数的剔除视图模型之间的区别 - Difference between knockout View Models declared as object literals vs functions JSON和JavaScript对象文字中的有效名称之间的区别 - Difference between valid names in JSON and JavaScript object literals {}和Object之间有什么区别? - What is the difference between {} and Object? 模板文字和标记模板文字之间的区别? - Difference between Template literals and Tagged template literals? Object,Object和[1:Object,2:Object]之间有什么区别? - What is the difference between Object, Object and [1: Object, 2: Object]? 在Object.create中使用对象文字和函数表达式之间有区别吗? - Is there a difference between using object literals vs function expressions with Object.create?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM