Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中,是否可以单独调用新运算符而不指定变量?_Javascript_Function_New Operator_Self Invoking Function - Fatal编程技术网

在JavaScript中,是否可以单独调用新运算符而不指定变量?

在JavaScript中,是否可以单独调用新运算符而不指定变量?,javascript,function,new-operator,self-invoking-function,Javascript,Function,New Operator,Self Invoking Function,我是JS新手,有一段来自教程的JavaScript代码: class TypeWriter{ constructor(x,y){ this.x = x; this.y = y; this.type(); } } TypeWriter.prototype.type() = function(){......} 到目前为止一切都很好,但后来我对新操作员的名称感到困惑: function init()

我是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()方法被自动调用,这让我不知所措。这背后的原因是什么?为什么只通过调用新的打字机()来调用type()

根据我的理解,type()和新操作符应该是这样的:

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


有人能向我解释一下它是如何工作的吗?提前谢谢。

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

这就是构造函数的样子:

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

另外,将
type
方法添加到原型中的方式有一个小错误,即在
type
之后没有插入括号。(请参阅下面的代码片段)

类打字机{
构造函数(x,y){
这个.x=x;
这个。y=y;
this.type();
}
}
TypeWriter.prototype.type=函数(){
log(“调用的类型方法”);
}
常量打字机=新打字机(10,20);//方法调用一次

typeWriter.type();//方法再次调用
TypeWriter.prototype.type()
这是调用type函数。不分配它。您还调用了
this.type()代码。当你在类上使用
new
操作符时,
constructor
中的代码将运行,你在
constructor
@adiga中有
this.type()
,谢谢你的回答。非常感谢!这么详细的回答!答案被接受了,但我的声誉太低了,不能投票支持它。@Katrine.R别担心!