Exporting Objects with the Exports Object

后端 未结 4 1583
野趣味
野趣味 2021-02-02 14:36

Say I have one .js file containing a javascript object. I want to be able to access that object and all of its functionality from another .js file in t

4条回答
  •  情书的邮戳
    2021-02-02 14:52

    the simplest approach, in my opinion:

    write Person.js: (note it comes with ctor)

    module.exports = function (firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.fullName = function () { 
            return this.firstName + ' ' + this.lastName;
        }
    }
    

    and consume it:

    var person = require('./Person.js');
    
    var person1 = new person('James', 'Bond');
    
    console.log(person1.fullName());
    

    note that in this simple solution all methods are "public".

    ref: https://www.tutorialsteacher.com/nodejs/nodejs-module-exports

提交回复
热议问题