使用";。调用;创建一个新的JavaScript对象,而不是;新";

使用";。调用;创建一个新的JavaScript对象,而不是;新";,javascript,prototype,Javascript,Prototype,我在Chrome控制台上尝试了以下命令。我可以使用new(下面的第2行)创建对象,但是使用call不起作用。有人能解释一下原因吗 function ObjConstructor(){ this.sample = 1}; let withNew = new ObjConstructor(); let usingCall = ObjConstructor.call({}); usingCall undefined //output that came on console, this is

我在Chrome控制台上尝试了以下命令。我可以使用new(下面的第2行)创建对象,但是使用call不起作用。有人能解释一下原因吗

function ObjConstructor(){ this.sample = 1};

let withNew = new ObjConstructor();

let usingCall = ObjConstructor.call({});

usingCall
undefined  //output that came on console, this is not a command

withNew
ObjConstructor {sample: 1} //output that came on console

new
执行以下几项操作:

  • 创建对象
  • 值设置为该对象
  • 使函数在默认情况下返回该对象
您的代码:

  • 使用
    {}
  • 使用
    call()

…但不是做最后一件事。函数中没有
return
语句,因此它返回
undefined

调用
的结果是函数返回的结果。您的
ObjConstructor
没有返回任何内容,因此调用它的结果是
未定义。

相反,使用
new
时,会创建一个新对象并将其传递给函数,除非函数返回非
null
对象,否则为
new
创建的对象是
new
表达式的结果

这就是为什么
新版本可以工作,而
调用不能工作的原因

还要注意,
call
根本不创建对象。在
ObjConstructor.call({})
中,创建对象的是
{}
,而不是
call
。它的原型不会是
ObjConstructor.prototype
。(
{}
是一个原始对象初始值设定项,因此对象将有
对象.prototype
作为其原型。)

试试这个。 或者看看这个->

var MyType=function(_param1,_param2){
this.param1=_param1;
this.param2=_param2;
this.ShowParam=函数(){
警报(this.param1+“-”+this.param2);
}
}
var测试=新的MyType(“参数测试1”、“参数测试2”);
警报(test.param1+“-”+test.param2);
var test2=新的MyType(“参数测试1.2”、“参数测试2.2”);
警报(test2.param1+“-”+test2.param2);
test.ShowParam();
test2.ShowParam();

Great Inputs Quentin,T.J.C.“.call”在设置继承时与“this”一起使用时工作顺利,因为这是一个对象,新属性被添加到其中,无需返回任何内容;)感谢您的输入,我知道该对象,但我想了解创建该对象的其他替代方法。