开发者

Javascript singleton: access outer attribute from inner function

// 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 si开发者_如何学运维ngleton 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)?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜