为什么函数在构造函数中声明时不使用 new 关键字?
Why functions don't use new keyword while being declared in constructors?
函数中的示例函数声明:
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
是运算符。它分配一个对象实例(并为其分配一个原型)。您创建的函数不是任何类型 class 的实例,也不会创建多个副本。静态声明定义了将存在的唯一实例。
函数中的示例函数声明:
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
是运算符。它分配一个对象实例(并为其分配一个原型)。您创建的函数不是任何类型 class 的实例,也不会创建多个副本。静态声明定义了将存在的唯一实例。