gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:48:02 25 4
gpt4 key购买 nike

函数中的示例函数声明:

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 是一个运算符。它分配一个对象实例(并为其分配一个原型(prototype))。您创建的函数不是任何类型的类的实例,并且不会创建多个副本。静态声明定义了唯一存在的实例。

关于javascript - 为什么函数在构造函数中声明时不使用 new 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33224104/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com