2

我在 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
4

3 回答 3

3

new做几件事,包括:

  • 创建对象
  • this值设置为该对象
  • 使函数默认返回该对象

你的代码:

  • 手动创建一个对象{}
  • this值设置为该对象call()

......但不做最后一件事。函数中没有return语句,所以返回undefined.

于 2019-03-15T10:53:00.283 回答
3

结果call是函数返回的任何内容。你ObjConstructor没有返回任何东西,所以调用它的结果是undefined.

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

这就是为什么该new版本有效但call无效的原因。

另请注意,call它根本不会创建对象。在您的ObjConstructor.call({})中,创建对象的是{},不是call。它不会有ObjConstructor.prototype它的原型。({}是一个原始对象初始化器,因此该对象将Object.prototype作为其原型。)

于 2019-03-15T10:53:52.953 回答
0

尝试这个。或者看看这个-> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

var MyType = function(_param1,_param2){
this.param1 = _param1;
this.param2 = _param2;

this.ShowParam = function(){
  alert(this.param1+" - "+this.param2);
  }
}

var test = new MyType("PARAM TEST 1","PARAM TEST 2");

alert(test.param1+" - "+test.param2);


var test2 = new MyType("PARAM TEST 1.2","PARAM TEST 2.2");

alert(test2.param1+" - "+test2.param2);

test.ShowParam();
test2.ShowParam();

 

于 2019-03-15T12:20:00.260 回答