How does the 'class' syntax work in javascript?

Viewed 76

I am working on building an api service for a react native app and I am curious what the difference is between a function that sets up instances and then returns an object with closures around the api functions like this:

export default AuthApiService = (bearerToken) => {

    const instance = axios.create({
            baseURL: `http://${BASE_URL}`,
            timeout: 5000,
            headers: {
                'Content-Type': 'application/json',
                 Authorization: `Bearer ${bearerToken}`
            }
        })

    const signup = async (email, password) => {
        try {
            const response = await instance.post(`/users`, {
                email,
                password
            })
            return response.data
        } catch (err) {
            console.log('error in signup api call', err, err.response)
            throw err
        }
    }

    const facebookLogin = async () => {
        try {
        } catch (err) {}
    }

    return {
        signup,
        facebookLogin
    }
}

and a class that creates the object with the constructor syntax and has direct access to the methods of the object like this:

export default class AuthApiService {
    constructor(bearerToken) {
        this.instance = axios.create({
            baseURL: `http://${BASE_URL}`,
            timeout: 5000,
            headers: {
                'Content-Type': 'application/json',
                 Authorization: `Bearer ${bearerToken}`
            }
        })
    }

    signup = async (email, password) => {
        try {
            const response = await this.instance.post(`/users`, {
                email,
                password
            })
            return response.data
        } catch(err) {
            console.log('error in signup api call', err, err.response)
            throw err
        }
    }

    facebookLogin = async () => {
        try {

        } catch(err) {

        }
    }
}

In javascript class syntax basically just a function that creates an object with a different prototype?

Also if you could give opinions about which approach is "better"?

Thanks

2 Answers

Just like any other programming language, classes essentially just follow the object-oriented approach. There really isn't much of a difference besides the syntax and how it is understood.

In JavaScript particularly, a key difference is the use of the constructor function to create an object from a class. This constructor can later be tracked, whereas a regular function this cannot happen. JavaScript technically doesn't even have "classes". The class syntax was added with ES6, and it's pretty much a standard function under the hood.

Regarding which approach is best, it really is up to you. In my opinion, less is more, and simplicity and readability are the most important thing in programming. I would familiarize yourself with both approaches, especially if you plan on working with React because of the pre-hooks era and the current hooks trend.

I would recommend staying away from classes if at all possible (In Javascript) checkout this video on factory functions with fun fun function for why factory functions are usually better. Class.prototype can be tricky, and the "this" keyword in javascript can be tricky without properly binding method calls with .bind(this). React even has you bind the method in the class.

This is not to say classes are incorrect in any way, just that they can be unnecessarily complicated in javascript.

Related