“new Array(n)”和“Array(n)”有什么区别

What the different between `new Array(n)` and `Array(n)`

本文关键字:Array 什么 区别 new      更新时间:2023-09-26

如果它们都调用构造函数"数组"并生成一个对象,那有什么不同?

我知道如果我们在没有new的情况下创建一些对象,我们会失去this

function Animal(name) {this.name = name}
var duck = Animal('duck'); // undefined

但这如何适用于new Array(n)Array(n)

没有区别。查看这篇文章:

你永远不需要在 JavaScript 中使用新的 Object()。使用对象而是文字 {}。同样,不要使用新的 Array(),使用 array而是文字 []。JavaScript 中的数组的工作方式与数组完全不同在 Java 中,使用类似 Java 的语法会让你感到困惑。

不要使用新数字、新字符串或新布尔值。这些形式产生不必要的对象包装器。只需改用简单的文字即可。

......

......。

所以规则很简单:我们唯一应该使用 new 运算符的时候是以调用伪经典构造函数。调用构造函数,使用new是强制性的。

Array的这种行为在规范中描述。您可以像这样获得相同的行为

function Animal(name) {
  if(!(this instanceof Animal)) {
     return new Animal(name);
  } 
  this.name = name
}
var duck = Animal('duck'); //Animal {name: "duck"}

但更好的主意是遵循一个简单的代码样式约定,即所有以大写字母开头的函数都是构造函数,应该用 new 调用。并设置一个你喜欢检查代码的 linter 遵循此规则。

JavaScript 使用原型继承。当您使用new命令时,它会继承自Object 。如果你想从用户定义的对象(例如动物)继承,你需要使用new Animal()或不使用new你可以通过以下方式完成。

   // Function object acts as a combination of a prototype 
     // to use for the new object and a constructor function to invoke:
     function Animal(name){
      this.name = name
     }
     var inheritFrom = function(parent, prop){
      // This is how you create object as a prototype of another object
      // var x = {} syntax can’t do this as it always set the newly
      //created object’s prototype to Object.prototype.
      var obj = Object.create(parent.prototype);
     // apply() method calls a function with a given this value 
     //and arguments provided as an array 
     parent.apply(obj, [prop]);
     return obj
    }
    var duck = inheritFrom(Animal, 'duck');
    console.log(duck.name);  // ‘duck’