简体   繁体   English

javascript 中的“类”语法如何工作?

[英]How does the 'class' syntax work in javascript?

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: 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:和一个 class 使用构造函数语法创建 object 并可以直接访问 object 的方法,如下所示:

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?在 javascript class 语法基本上只是一个 function ,它创建一个具有不同原型的 ZA8CFDE6331BD59EB2AC96F8911C4B6666?

Also if you could give opinions about which approach is "better"?另外,您是否可以就哪种方法“更好”发表意见?

Thanks谢谢

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.特别是在 JavaScript 中,关键区别在于使用constructor function 从 ZA2F2ED4F2AC96F8911B59EB2AC96F8911C4B666Z 创建 object。 This constructor can later be tracked, whereas a regular function this cannot happen.稍后可以跟踪此构造函数,而常规 function 则不会发生这种情况。 JavaScript technically doesn't even have "classes". JavaScript 在技术上甚至没有“类”。 The class syntax was added with ES6, and it's pretty much a standard function under the hood. class 语法是在 ES6 中添加的,它在引擎盖下几乎是一个标准的 function。

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.我会熟悉这两种方法,特别是如果你计划使用 React,因为 pre-hooks 时代和当前的 hooks 趋势。

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.如果可能的话,我建议远离课堂(在 Javascript 中)查看这个关于工厂函数的视频,其中包含有趣的 function ,了解为什么工厂函数通常更好。 Class.prototype can be tricky, and the "this" keyword in javascript can be tricky without properly binding method calls with.bind(this). Class.prototype 可能很棘手,如果没有正确绑定方法调用 with.bind(this),javascript 中的“this”关键字可能会很棘手。 React even has you bind the method in the class. React 甚至让你在 class 中绑定方法。

This is not to say classes are incorrect in any way, just that they can be unnecessarily complicated in javascript.这并不是说类在任何方面都不正确,只是它们在 javascript 中可能会变得不必要地复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM