Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第8条:尽量少用全局对象 #8

Closed
xiaoluoboding opened this issue Jul 22, 2016 · 0 comments
Closed

第8条:尽量少用全局对象 #8

xiaoluoboding opened this issue Jul 22, 2016 · 0 comments
Assignees

Comments

@xiaoluoboding
Copy link
Owner

xiaoluoboding commented Jul 22, 2016

笔记

  • 定义全局变量会污染共享的公共命名空间,并可能导致意外的命名冲突
  • 全局命名空间是JavaScript程序中独立的组件进行交互的唯一途径
  • JavaScript的全局命名空间也被暴露为在程序全局作用域中可以访问的全局对象,该对象作为this关键字的初始值
  • 添加或修改全局变量会自动更新全局对象,类似地,更新全局对象也会自动地更新全局命名空间
  • 特性检测是一种使得程序在平台特性集合的变化中依旧健壮的相对简单的方法
/*
 * 这是一张 JavaScript 代码草稿纸。
 */

function averageScore(players) {
    var i, n, sum;
    sum = 0;
    for (var i = 0, n = players.length; i < n; i++) {
        sum += players[i];
    }
    return sum / n;
}

averageScore([7, 8, 9])

/*
8
*/
// 添加或修改全局变量会自动更新全局对象
this.foo;
/*
undefined
*/
foo = "global foo";
this.foo;
/*
global foo
*/

// 更新全局对象也会自动地更新全局命名空间
var foo = "global foo";
this.foo = "changed";
foo
/*
changed
*/ 

全局对象的**特殊用途:**由于全局对象提供了全局环境的动态反应机制,所以可以使用它查询一个运行环境,检测在这个平台下哪些特性是可用的。

typeof(this.JSON)
/*
object
*/

提示

  • 避免声明全局变量
  • 尽量声明局部变量
  • 避免对全局对象添加属性
  • 使用全局对象来做平台特性检测
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant