views:

94

answers:

4

I've been trying to learn closures (in Javascript), which kind of hurts my brain after way too many years with C# and C++. I think I now have a basic understanding, but one thing bothers me: I've visited lots of websites in this Quest for Knowledge, and nowhere have I seen a word (or even a simple two-word phrase) that means "a set of Javascript closures that share a common execution context". For example:

function CreateThingy (name, initialValue)
{
    var myName = name;
    var myValue = initialValue;

    var retObj = new Object;

    retObj.getName = function() { return myName; }
    retObj.getValue = function() { return myValue; }
    retObj.setValue = function(newValue) { myValue = newValue; }

    return retObj;
};

From what I've read, this seems to be one common way of implementing data hiding. The value returned by CreateThingy is, of course, an object, but what would you call the set of functions which are properties of that object? Each one is a closure, but I'd like a name I can used to describe (and think about) all of them together as one conceptual entity, and I'd rather use a commonly accepted name than make one up.

Thanks!

-- Ed

+1  A: 

You could call it a class, but it's just a hash table with a bunch of entries, some of which are functions (or closures). The more idiomatic way to do this in Javascript is through the use of prototypes.

Some links to help you:

Jordão
+3  A: 

Crockford popularized the term "privileged method" to name the functions that have access to the scope of its constructor (where the private members are declared).

I would call them "A set of JavaScript functions that share a common enclosing scope".

The "execution context" part of the phrase you post, can create confusion between the Execution Contexts described in the specification, the this value, which also is popularly known as "the function context" or "object context", and the function scope, which is really what is being referenced here.

CMS
A: 

Its close to the module pattern. Use an expression like so:

var thingy = (function(specObj) {
    var my = {},
        privateVar = blah,
        someOtherPrivateVar = [];

    my.getSomeVal() {
        return specObj.someVal;
    }
    my.getAnotherVal() {
        return specObj.AnotherVal;
    }
}({
    someVal: "value",
    anotherVal: "foo"
}));

I initialized with an object literal because using a named object would allow the state of thingy to be changed by changing the named object. There are other options to do this.

Here's another good link on variations of the module pattern: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth

Almost goes without saying, but Crockford's Javascript: The Good Parts contains a good treatment of this style and its specific benefits.

jasongetsdown
A: 

Closures with shared bindings?

Flavius Stef