1
// i = inner, o = outer, f=function, a=attribute
var singleton = function() {
 var iF = function() {
    return this.oA; // returns undefined
 }
 return {
  oF: function() {
   this.oA = true;
   return iF();
  },
  oA: false
 };
}();

singleton.oF();

If singleton were a class (as in a class-based language), shouldn't I be able to access oA through this.oA?

The only way I've found of accessing oA from iF is by doing:

return singleton.oA; // returns true (as it should)

I don't know why, but accessing oA through the singleton base object makes me feel kind of... dirty. What am I missing? What is this.oA actually referring to (in a scope sense of view)?

1
  • The problem you're having is that this refers to window in that context, but I'm not sure exactly what you're after here... Commented Jul 9, 2010 at 13:12

1 Answer 1

1

The main point here is that there are no classes in javascript. You need to live without them. You can only emulate some of their characteristics.

The this keyword in javascript refers to the object which invoked the function. If it is a function in the global object this will refer to window. If it is a constructor function and you invoke it with the new keyword, this will refer to the current instance.

There is a simple thing you can do, if you want to keep oA public, and access it from a private function.

// i = inner, o = outer, f=function, a=attribute
var singleton = (function() {

 // public interface
 var pub = {
  oF: function() {
   this.oA = true;
   return iF();
  },
  oA: false
 };

 // private function
 var iF = function() {
    return pub.oA; // returns public oA variable
 }

 // return public interface
 return pub;
})();​

Notice that I wrapped the whole singleton function in parens. The reason this convention is so popular is that it helps you to know if a function will be executed immediately (as in this case). Imagine if your function gets bigger, and when you look at the code it wouldn't be obvious if singleton is a function or an object that a self-invoking function returns. If you've got the parens however, it is obvious that singleton will be something that the function returns immediately.

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution is spot on. Thanks for your note on paranthesis as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.