nik
nik

Reputation: 303

Class references to local module function

Say, there is a module that exports a class. Does it violates any principles to reference declared locally functions from class method?

An example:

function doSomething() {}

class Cat {
    constructor () {}
    say () {
        doSomething()
        return 'meow'
    }
}

module.exports.Cat = Cat

Upvotes: 1

Views: 27

Answers (1)

Mark
Mark

Reputation: 92440

Not only does this not violate any principles, it's a good way to organize behavior. doSomething() will be a function that is private to the module. This makes it easy to expose a consistent interface to your class without worrying about implementation.

So for example in mod.js:

function doSomething() {
    console.log("I'm doing something")
}

class Cat {
    constructor () {}
    say () {
        doSomething()
    }
}

module.exports.Cat = Cat

Now use it:

var mod = require('./mod')
var cat = new mod.Cat
cat.say()
// logs to console: "I'm doing something"

Upvotes: 2

Related Questions