将类与构造函数对象一起使用 [英] using classes with constructor objects

查看:84
本文介绍了将类与构造函数对象一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在另一个类中使用带有构造函数对象的类.但是,如何正确地调用该类呢?例如:如何在2类中使用1类?

I am trying use a class with a constructor object, in another class. But how do I call that class correctly? eg: How do i use Class 1, in Class 2?

下面的示例根据axios调用的响应创建对象. _object应该是我从getData()得到的任何东西.我不确定这是否是正确的方法.但是我该如何在另一个类中使用构造函数调用此类?理想情况下,我希望能够查询对象的属性,并在其他类中使用它们,但是我不确定如何正确调用该类.

The example below is creating an object, from a response from an axios call. The _object should be whatever I get from getData(). Im not sure if this is the right approach. But how do i then call this class with the constructor, in another class? Ideally I want to be able to query the properties of the object, and use them in the other class, but Im not sure how to call the class properly.

第1类:

export class MyClass {

    private _object: any;

    constructor(object: any) {
        this._object = object;
    }

    public static async getData() {
        return axios.get(url)
            .then(response => response.data)
            .catch((error) => {
                console.log(error);
            });
    }

    public static async getCurrentData() {
        return new MyClass(await this.getData());
    }

}

尝试通过构造函数对象在另一个类中使用它:

Trying to use this in another class, with constructor object:

第2类:

new MyClass(object);  // cannot find name object

new MyClass();  // without constuctor object, Expected 1 arguments, but got 0. An argument for 'object' was not provided.'

我在这里问了相关问题: 返回构造函数对象的属性

Ive asked related question here: return properties of constructor object

推荐答案

您的构造函数需要一个对象作为其参数.因此,要构造MyClass的对象,您需要执行以下操作:

Your constructor requires an object as its argument. So to construct an object of MyClass, you'll need to do something like:

let obj = new MyClass({}) // construct with an empty object as the arg
// or:
let argObj = {a: 123}
let obj = new MyClass(argObj)

这篇关于将类与构造函数对象一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆