简体   繁体   English

无法使用对 function 的调用方法创建 object。 如何使用调用方法创建 object?

[英]Not able to create object using call method to the function. How can I create an object using call method?

Here I have created a constructor function.这里我创建了一个构造函数 function。 I want to create an object using call method to this function.我想使用调用此 function 的方法创建一个 object。 I have used the empty object as the current object and passed an argument.我使用空的 object 作为当前的 object 并传递了一个参数。

 function Circle(radius){ this.radius = radius; this.draw = function(){ console.log('draw'); } } let cirlce1 = Circle.call({}, 1); console.log(cirlce1);

I am getting undefined in the console.我在控制台中变得不确定。 I want to know where have I gone wrong?我想知道我哪里出错了?

You have to return the current object in the Circle function.您必须在圈子 function 中返回当前的 object。 Here you are creating a variable equals to what Circle returns.在这里,您正在创建一个等于 Circle 返回的变量。 Because it's not returning anything, you get undefined.因为它没有返回任何东西,所以你得到了未定义的。 So you only have to add a return statement at the end returning this.因此,您只需在返回 this 的末尾添加一个 return 语句。 Which in this case is the empty object you passed originally in call.在这种情况下,它是您最初在通话中传递的空 object。

function Circle(radius){
    this.radius = radius;
    this.draw = function(){
        console.log('draw');
    }
    return this;
}

let circle = Circle.call({}, 1);
console.log(circle);

After that, your empty object now has the radius property and the draw method.之后,您的空 object 现在具有 radius 属性和 draw 方法。 Then you return it.然后你退货。 The result is saved in the circle variable.结果保存在 circle 变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM