我创建了两个对象。第一个正在按预期工作。
let working = {constructor: function(){
console.log("working");
}};
let notworking = {constructor(){
console.log("notworking");
}}
new working.constructor();
new notworking.constructor();
但第二个抛出错误。错误消息是:
Uncaught TypeError: notworking.constructor is not a constructor
在 Firefox 和 Chrome 上测试。
在 Firefox DevTools 中,对象本身看起来是一样的。构造方法有区别。
工作构造函数具有参数、调用者、长度和名称属性。
不工作的构造函数只有属性长度和名称。
那么这两个对象或构造函数有什么区别呢?
第二种语法是方法语法,它是在 ECMAScript 2015 中引入的。它们是almost等价,但还是有区别的。在第一个对象中,constructor
只是一个键,其值是一个函数。在第二个对象中,constructor
is a method https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions. 方法定义不可构造
方法不能是构造函数。如果您尝试实例化它们,它们将抛出 TypeError
From: MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions#method_definitions_are_not_constructable
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)