简体   繁体   中英

javascript es6 module variable vs static

Let's say we have these 2 classes, What are the differences of having a function in the module scope vs being a static class function, assuming doSomething doesn't require the this access. the only difference I can see is, module is "more private", is there any thing else?

Sample1.js

class Sample1 extends React.Component {
    static doSomething(input) {
        // ...
        return input2;
    }

    render() {
        if (Sample1.doSomething(x)) {
            return <div />;
        }
        return null;
    }
}
export { Sample1 };

Sample2.js

const doSomething = (input) => {
    // ...
    return input2;
};

class Sample2 extends React.Component {
    render() {
        if (doSomething(x)) {
            return <div />;
        }
        return null;
    }
}
export { Sample2 };

Well, in Sample1 doSomething is exposed, you can access it with Sample1.doSomething() , but in Sample2 scenario, the method won't be available outside the module scope, so yeah it is private.

Now, about the memory consumption, no matter how many instances you create, that static method it is allocated once, and it is accessible through the class only, not through the instances.

Does this make sense to you?

The only difference is testability. When a function is called as a method like Sample1.doSomething(x) , it can be spied or stubbed during testing.

A way that is more extendable is to refer static method like this.constructor.doSomething(x) . In this case the method can be extended in child class.

If the method is used only in class instances and never called as static (like in React component), it doesn't make sense to make it static. It can be defined as prototype method and be called like this.doSomething(x) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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