简体   繁体   English

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

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

sample function declaration in 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;
};

sample new function declaration : 示例新函数声明:

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

Why are we using new keyword while declaring a new function but not using new keyword while declaring it in a constructor?? 为什么我们在声明新函数时使用new关键字,而在构造函数中声明它时却不使用new关键字?

new is an operator. new是一个运算符。 It allocates an object instance (and assigns it a prototype). 它分配一个对象实例(并为其分配一个原型)。 The functions you create aren't instances of any sort of class, and are not going to be created in multiple copies. 您创建的函数不是任何类的实例,也不会在多个副本中创建。 The static declaration defines the only instance that will exist. 静态声明定义了将存在的唯一实例。

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

相关问题 如果JavaScript不支持经典继承,为什么我能够创建构造函数并使用新关键字? - If JavaScript doesn't support Classical inheritance why am I able to create constructors and use new keyword? 如何对 JQUERY 中没有操作的函数使用 THIS 关键字 - How to use THIS keyword for functions that don't have an action in JQUERY 为什么没有新关键字声明为函数的变量未定义? - why variable declared to function without new keyword is undefined? 使用“new”关键字(Phaser 3)声明时,容器不会呈现子项 - Container doesn't render children when declared by 'new' keyword (Phaser 3) 学习把手:如果我不使用`this`,为什么数据不传递到我的模板上 - Learning Handlebars: why isn't data being passed to my template if I don't use `this` 为什么反应组件作为 class 必须有`render`方法,而那些作为函数没有? - Why do react components as class must have `render` method, while those as functions don't? 为什么一些JavaScript构造函数不起作用? - Why are some JavaScript constructors not functions? 为什么这些功能不起作用 - Why do these functions don't work 为什么这些JavaScript函数未添加到该对象? - Why these JavaScript functions don't add to this object? 为什么函数没有[[Value]]属性? - Why don't functions have a [[Value]] attribute?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM