cancel
Showing results for 
Search instead for 
Did you mean: 

JavaScript Function Scoping (Script Snap)

ForbinCSD
Contributor

I thought about creating a ticket to ask this, then realized others probably could use this information as well…

When writing a script for a JavaScript snap, one can define all the subroutines as member functions within the “impl” object:

var impl = {
    input: input,
    output: output,
    error: error,
    log: log,

    // A real function would do a lot more than this
    doSomething: function( inputVal ) {
        return inputVal;
    },

    execute: function() {
        while (this.input.hasNext()) {
            var doc = this.input.next();
            ...
            var foo = this.doSomething(doc.baz);
            ...
            var wrapper = new java.util.HashMap();
            wrapper.put("original", doc);
            this.output.write(doc, wrapper);
        }
    }
};

However, some developers prefer making functions stand by themselves when they do not access other members of the object (thus, not needing to be a member themselves):

// A real function would do a lot more than this
function doSomething( inputVal ) {
    return inputVal;
};

var impl = {
    input: input,
    output: output,
    error: error,
    log: log,

    execute: function() {
        while (this.input.hasNext()) {
            var doc = this.input.next();
            ...
            var foo = doSomething(doc.baz);
            ...
            var wrapper = new java.util.HashMap();
            wrapper.put("original", doc);
            this.output.write(doc, wrapper);
        }
    }
};

My Question:
In terms of scoping (and memory usage), is there any difference between the two?
Particularly if there are multiple script snaps running at the same time in the same pipeline?

For example, suppose you have two script snaps, Script-1 and Script-2:
image

Clearly, var impl is a separate instance in each, otherwise you couldn’t have two script snaps in the same pipeline.

  1. If each snap has it’s own separate function doSomething() in the separate scripts, I’m assuming those are also outside of each other’s scope, is that correct?

  2. Since functions are first-class objects in JavaScript, does it consume more memory to make the functions external to the impl object, than to have them as members?

Inquiring minds want to know!

0 REPLIES 0