0

As you can see the in the code below, the class GitHub contains fetch api code to get data from api. But the question is why do we use at the end of that code: const git = new GitHub(); with () since as far as I know, new GitHub() creates new instance of an object and then RUN the code inside GitHub class. So, the question is why NEED to run the code after the creation of a new object

 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();
Pop
  • 77
  • 7
  • Github is a class and so if you want to instantiate an object from that class, you need to call the constructor. The () is there so you can pass in values if you need to set some properties to some values. You are "running" the constructor. Even if you don't pass in values, the constructor runs to set default values – Plzhelp Jul 18 '19 at 20:04

1 Answers1

2

Because when you declare a class and create a new instance of it, it instantly runs the constructor method.

JC Hernández
  • 740
  • 3
  • 12