简体   繁体   English

试图了解javascript中对象的区别

[英]Trying to understand the difference of objects in javascript

In the code examples below, I understand how alternative 1 and 2 work, but Im trying to understand the third alternative. 在下面的代码示例中,我了解了替代方法1和2的工作方式,但是我试图理解第三个替代方法。 What kind of object is this and why does it start with a bracket before the function like this: (function and Why does it end with a double bracket like this: () . Just curious and would like to know what is what and the difference? 这是什么类型的对象,为什么它以这样的函数之前的括号开头:( (function以及为什么以这样的双括号结尾:( () 。很好奇,想知道这是什么和区别?

Alternative 1: (Object Literals) 备选方案1 :(对象文字)

var something = {
 rows: 12;
 cols: 6;
  };

Alternative 2: (Function Objects) 备选方案2 :(函数对象)

var something = function(x,y) {
    return x + y;
}

Alternative 3: ?? 备选方案3:??

var something = (function() {
    var settings = {
    rows : 10,
    cols : 3,
    number : 2
    };
    })();

Alternative 3 sets your "something" variable to the return of the function. 备选方案3将“ something”变量设置为函数的返回值。 () actually executes the function. ()实际上执行该功能。

I will use something from MDN to show the benefits with closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures 我将使用MDN中的一些内容来展示闭包的好处: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

var Counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  };   
})();

alert(Counter.value()); /* Alerts 0 */
Counter.increment();
Counter.increment();
alert(Counter.value()); /* Alerts 2 */
Counter.decrement();
alert(Counter.value()); /* Alerts 1 */

In your code, alternative 3 will leave undefined in something variable, reason being your function is not returning any value. 在您的代码中,替代方案3将在变量中保持未定义状态,原因是您的函数未返回任何值。

A very good link already posted above by @Felix. @Felix已经在上面发布了一个很好的链接。 This is basically an IIFE which is invoked immediately and return value of that function would be assigned to something variable. 基本上,这是一个IIFE,可立即调用该IIFE,并且该函数的返回值将分配给某些变量。

One of the key goal in such pattern typically is to hide some state in a closure. 这种模式的主要目标之一通常是在闭包中隐藏某些状态。 Any variables defined in the function would make the state. 函数中定义的任何变量都会进入状态。 These variables would be accessible to the functions in the returned object but not to the outside world. 这些变量对于返回的对象中的函数将是可访问的,但对于外部世界将不可用。

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

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