原文地址:
1). JavaScript Best Practices: http://www.w3schools.com/js/js_function_closures.asp
2). JavaScript Closures http://www.w3schools.com/js/js_function_closures.asp
3). JavaScript 严格模式 http://blog.csdn.net/supersky07/article/details/14129179
1. 关于全局变量
- 尽可能减少使用全局变量(去表示数据类型、对象和函数),全局变量或函数可能被所引用的其他JS 脚本所覆盖。
- 网页中,全局变量属于 Winow 这个对象
- 当定义变量时没有使用关键词 var,这个变量讲被定义成全局的,即使它在某个函数内部创建
2. 闭包
var add = (function () { var counter = 0; return function () {return counter += 1;} })(); add(); add(); add(); // the counter is now 3
变量 add 的初始值为 一个self-invoking函数的返回值,这个self-invoking的函数只执行一次。通过上述代码,我们成功地将 add 变成了函数,而且它还可以访问那个函数的的parent scipe的变量 - counter。
这个例子就叫做 JavaScript 闭包,使得 JS 中实现“private” 变量成为可能。上述例子中的 counter 是由匿名函数的scope保护的,而且只能通过 add 函数访问。
3. Strict mode
- Strict mode下,不允许未(利用 var)声明的变量
- 如果一个内部方法定义在一个声明了"use strict"的外部方法内,那么它也会启用严格模式。
- 在严格模式中,this的值不会被自动的变成一个对象。最值得注意的是,当call或apply的第一个参数为null或undefined时,被引用方法中的this的值将不会被转换成全局对象。(译者注:非严格模式下会转化成window,严格模式下为null)
4. 将变量声明放在函数或脚本的最上面,声明时将变量初始化
5. 不要使用 new Object()
- Use {} instead of new Object()
- Use "" instead of new String()
- Use 0 instead of new Number()
- Use false instead of new Boolean()
- Use [] instead of new Array()
- Use /()/ instead of new RegExp()
- Use function (){} instead of new function()
6. 注意类型自动转换
var x = "Hello"; // typeof x is a string x = 5; // changes typeof x to a number
当进行数学运算时, JS 可以将数字转成字符串
var x = 5 + 7; // x.valueOf() is 12, typeof x is a number var x = 5 + "7"; // x.valueOf() is 57, typeof x is a string var x = "5" + 7; // x.valueOf() is 57, typeof x is a string var x = 5 - 7; // x.valueOf() is -2, typeof x is a number var x = 5 - "7"; // x.valueOf() is -2, typeof x is a number var x = "5" - 7; // x.valueOf() is -2, typeof x is a number var x = 5 - "x"; // x.valueOf() is NaN, typeof x is a number
两个字符串相减,不会出错而是返回 NaN (Not a Number)
"Hello" - "Dolly" // returns NaN
7. 三个等号
== 两个等号做对比时,会将操作数做类型转换;
=== 三个等号做对比时,会强制比较操作数类型的值
0 == ""; // true 1 == "1"; // true 1 == true; // true 0 === ""; // false 1 === "1"; // false 1 === true; // false
8. 当一个函数调用时没有传递参数,参数值将被设置为 undefined
9. 避免使用eval()- eval()可以将text 作为code执行
时间: 2024-08-04 19:48:16