简体   繁体   English

使用功能的私有功能的引用创建对象

[英]Creating Objects with the references of a function's private functions

I came across a snippet and I doubt it can be written in a straightforward way. 我遇到了一个摘要,我怀疑它是否可以以简单的方式编写。 Could someone please tell me what is the difference between the below two snippets: 有人可以告诉我以下两个摘要之间的区别是什么:

var printer = (function () {
  var printerInstance;
  var obj = {
     f1: function() {},
     f2: function() {}
  };
  return {
     getInstance: function() {
       if(!printerInstance) {
         printerInstance = obj;
       }
       return printerInstance;
     }
   };
})();

And

var printer = (function () {
     var printerInstance;
     function create() {
       function f1() {}
       function f2() {}
       return {
          f1: f1,
          f2: f2
       }
     }

     return {
       getInstance: function() {
         if(!printerInstance) {
           printerInstance = create();
         }
         return printerInstance;
       }
     };
})();

I did not understand why the object has been created inside a function in the second example. 我不明白为什么在第二个示例中的函数内部创建了对象。 Please clarify. 请澄清。

Well, the first one has one object called obj for all calls, the second one creates a new one for every call. 好吧,第一个对象在所有调用中都有一个名为obj对象,第二个obj为每个调用都创建了一个新对象。

So for example say that it is : 举例来说,它是:

var obj = {
   var counter = 0;
   f1: function() { return counter++; },
   f2: function() {}
};

and the second one is: 第二个是:

function create() {
  var counter = 0;
  function f1() { return counter++; }
  function f2() {}
  return {
     f1: f1,
     f2: f2
  }
}

In the first case, there is one object with one counter which will be referenced by all getInstance invocations (where printerInstance equals null ). 在第一种情况下,有一个对象带有一个counter ,所有getInstance调用(其中printerInstance等于null )都将引用该对象。 So this is more like a Singleton . 因此,这更像是Singleton

In the second case, each invocation of getInstance will have it's own counter and count independantly. 在第二种情况下,每次对getInstance调用都将拥有其自己的计数器并独立计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM