为什么函数在构造函数中声明时不使用new关键字

Why functions don't use new keyword while being declared in constructors?

本文关键字:new 关键字 声明 函数 构造函数 为什么      更新时间:2023-09-26

function中的示例函数声明:

function Rectangle(height, width) {
  this.height = height;
  this.width = width;
  this.calcArea = function() {
      return this.height * this.width;
  };
  // put our perimeter function here!
  this.calcPerimeter = function() {
    return 2 * this.height + 2 * this.width;
};

新函数声明示例:

var actions = new function() {
    console.log("this is to do something");
}

为什么我们在声明新函数时使用new关键字,而在构造函数中声明时不使用new关键字?

new是操作符。它分配一个对象实例(并为其分配一个原型)。您创建的函数不是任何类型类的实例,也不会在多个副本中创建。静态声明定义了唯一存在的实例。