zoukankan      html  css  js  c++  java
  • 模块模式——属性

      私有变量 与 自执行匿名函数 返回对象上的属性 的理解

    // 自执行匿名函数的值保存在变量prison里面
    var prison = (function () {
      var prisoner_name = 'WangMing',
          jail_term = '20 year term';
    
      // 自执行匿名函数返回了一个对象,对象上的属性正是我们想要的
      return {
        prisoner: prisoner_name + ' - ' + jail_term,
        sentence: jail_term
      };
    })();
    
    // prison.prisoner_name未定义,因为它不是自执行匿名函数返回对象上的属性
    console.log( prison.prisoner_name );
    // this outputs 'WangMing - 20 year term'
    console.log(prison.prisoner);
    // this outputs '20 year term'
    console.log(prison.sentence);
    

      自执行匿名函数会立即执行,返回一个拥有prisoner和sentence属性的对象。匿名函数没有保存在prison变量中,因为匿名函数被执行了:匿名函数的返回值保存在变量prison中。

      在全局作用域中添加了prison变量,没有添加prisoner_name和jail_term变量。在稍大一点的模块中,减少全局变量是很重要的。

      单页应用很庞大,不能定义在一个文件中。使用自执行匿名函数封装私有变量返回自执行匿名函数对象上的属性,隐藏私有变量,调用对象上的属性形成模块。将该文件分成一个个的模块,每个模块都有它自己的私有变量。

     

  • 相关阅读:
    题解 CF171G 【Mysterious numbers
    题解 P1157 【组合的输出】
    题解 P3955 【图书管理员】
    题解 P2036 【Perket】
    题解 CF837A 【Text Volume】
    题解 CF791A 【Bear and Big Brother】
    题解 CF747A 【Display Size】
    题解 P1332 【血色先锋队】
    题解 P2660 【zzc 种田】
    题解 P4470 【[BJWC2018]售票】
  • 原文地址:https://www.cnblogs.com/nodejsxxh/p/4422109.html
Copyright © 2011-2022 走看看