new function()和new函数之间的区别

时间:2019-07-18 19:16:09

标签: javascript

您可以在下面的代码中看到,类GitHub包含获取api代码以从api获取数据。但是问题是为什么我们在该代码的末尾使用:const git = new GitHub();用()表示,因为据我所知,new GitHub()创建对象的新实例,然后在GitHub类中运行代码。因此,问题是,为什么需要在创建新对象后运行代码

 class GitHub{
    constructor(){
        this.clientID='6ea9567c0f22d48fb20e';
        this.clientSecret='a4ec6e6b2040ddd5d197079014f8a4e0fb7fe839';
        this.repos_count=5;
        this.repos_sort='created: asc';
    }

    async getUser(user){
        let response = await fetch(`https://api.github.com/users/${user}?clientID=${this.clientID}&clientSecret=${this.clientSecret}`);
        let repoResponse = await fetch(`https://api.github.com/users/${user}/repos?per_page=${this.repos_count}&sort=${this.repos_sort}?clientID=${this.clientID}&clientSecret=${this.clientSecret}`);

        let parsedJson = await response.json();
        let reposJson = await repoResponse.json();

        return {
            data:parsedJson,
            reposJson
        }
    }        
}

const git = new GitHub();

1 个答案:

答案 0 :(得分:2)

因为当您声明一个类并创建一个新实例时,它会立即运行构造函数方法。

相关问题