首页 > 解决方案 > 无法使用对函数的调用方法创建对象。如何使用调用方法创建对象?

问题描述

在这里,我创建了一个构造函数。我想使用调用此函数的方法创建一个对象。我使用空对象作为当前对象并传递了一个参数。

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



let cirlce1 = Circle.call({}, 1);

console.log(cirlce1);

我在控制台中变得不确定。我想知道我哪里出错了?

标签: javascript

解决方案


您必须在 Circle 函数中返回当前对象。在这里,您正在创建一个等于 Circle 返回的变量。因为它没有返回任何东西,所以你得到了未定义的。因此,您只需在返回 this 的末尾添加一个 return 语句。在这种情况下,它是您最初在调用中传递的空对象。

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

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

之后,您的空对象现在具有 radius 属性和 draw 方法。然后你退货。结果保存在 circle 变量中。


推荐阅读