在 JavaScript 中单独调用新运算符而不分配给变量?

Call the new Operator be called individually without assigning to a variable in JavaScript?

我是 JS 新手,有一段 JavaScript 教程中的代码:

class TypeWriter{
      
      constructor(x,y){
           this.x = x;
           this.y = y;
           this.type();
   }
}

TypeWriter.prototype.type() = function(){......}

到目前为止一切都很好,但后来我对新运算符的调用方式感到困惑:

function init(){
      const a,b;
      new TypeWriter(a,b);
}

函数运行良好,自动调用了type()方法,迷路了。背后的原因是什么?为什么只通过调用新的 TypeWriter() 来调用 type()?

按我的理解,type() 和 new 运算符应该是这样的:

const typeWriter = new TypeWriter(a,b);
typeWriter.type();

任何人都可以向我解释它是如何工作的吗?提前谢谢你。

当您使用 new 关键字实例化 class 的对象时,您基本上是在调用 class 的构造函数。并且构造函数中的所有代码都将 运行.

所以,这就是构造函数的样子:

this.x = x;
this.y = y;
this.type();

您传递给构造函数的两个参数被添加为对象 (x, y) 的属性。 现在,在第三行调用 type 方法,这就是为什么在实例化时立即调用 type 方法的原因。

此外,您将 type 方法添加到原型中的方式存在一个小错误,您没有在 type 之后加上括号。 (见下面的片段)

class TypeWriter {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.type();
  }
}

TypeWriter.prototype.type = function() {
  console.log("Type method called");
}

const typeWriter = new TypeWriter(10, 20); // Method called once
typeWriter.type(); // Method called again

如果您不想在实例化时调用 type 方法,您可以简单地从构造函数中删除它的调用。 (见下面的片段)

class TypeWriter {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

TypeWriter.prototype.type = function() {
  console.log("Type method called");
}

const typeWriter = new TypeWriter(10, 20);
typeWriter.type(); // Method called once