简体   繁体   中英

How can I export module pattern function to another JavaScript file

I have two JavaScript files and would like to export the file with module pattern to another file. The file with module pattern, I would like to export only public members. When I try to execute the test, it says that "Calculator is not a constructor".

file: calculator.js

var Calculator = function(){
    var total = null;

    return {      
        add: function(x,y){
            total = x + y; 
        },

        getTotal: function(){
            return total;
        };

        display: function(){
            console.log(total);
        }
    }
}

second file: testCalculator.js

const calculatorObj = require('calculator.js');

describe("Calculator test suite", function(){
    var calculatorObj = new Calculator();

    it('Verify sum method', function() {        
        try{
            calculatorObj.add(5,5);                

            //assertive
            expect(10, calculatorObj.getTotal());
        }
        catch(err)
        {
            alert(err);
        }
    });
});

It is not working, because you need to export something before consuming it.

Add this code to make it work

module.exports = function(){
    var total = null;

    return {      
        add: function(x,y){
            total = x + y; 
        },

        getTotal: function(){
            return total;
        };

        display: function(){
            console.log(total);
        }
    }
}

do I have to list all the function names that I want to export?

Yes, you have to export all things you want to import later. Or you can export one single object with all code you need.

do i need to use "import" or "require()"

For Node.js, require is common practice. Latest Node.JS supports import construction, but, at least for now, using require is preferable.

For browsers, you will use import notation.

And your function is not a classical constructor, please, take a look into the class notation

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