预编译
函数的预编译发生在函数执行的前一刻;
window.prompt ( ’ input ’ ) // 输入(字符串形式)
parsetInt(window.prompt(’ input ’ )); //转化成数字型;
未经声明的变量归window所有;
a = 123; or a = b = 123; ( 暗示全局变量 ) ;
一切声明的变量都是window的属性;
意思就是 var a = 123 --> window.a = 123;
若访问a(console.log(a)) -->其实就是访问 console.log(window.a);
typeof(null) ----> object
隐式类型
作用域精解
function a(){
function b(){
var b = 234;
}
var a = 123;
b();
}
var glob = 100;
a();
先创建一个 GO;
然后执行 a function 时 同时创建一个 a function 的 AO,顺便将a 的 AO放到最高;
b 创建它自己的 AO 的时候先拿过来的是 a function 执行后的结果:
b 创建的一个 AO 放在最高,形成下面这样的形式:
b 函数执行完后把自己的 AO 取消 ,b函数恢复到被定义的状态等待下一次执行;相当于切断 函数与 [[scope]] 0 之间的联系;
exmple:
function a() {
function b() {
function c() {
}
c();
}
b();
}
c();
用式子表示为这样:
a defined a.[[scope]] – > 0 : GO
a doing a.[[scope]] – > 0 : aAO
1 : GO
b defined b.[[scope]] – > 0 : aAO
1 : GO
b doing b.[[scope]] – > 0 : bAO
1 : aAO
2 : GO
c defined c.[[scope]] – > 0 : bAO
1 : aAO
2 : GO
c doing c.[[scope]] – > 0 : cAO
1 : bAO
2 : aAO
3 : GO
闭包
eg
内部的函数被保存到了外部,将会形成闭包;
闭包会导致原有作用域链不释放,造成内存泄漏(内存占用的多,剩的少)。
立即执行函数
有两种写法:
1.(function (){}()); W3C 建议第一种
2.(function (){})();
只有表达式才能被执行符号执行; (函数名字会被自动忽略)
/*
function() {
console.log('a');
}()
*/
..此函数不能被执行;
/*
var test=function () {
console.log('a');
}()
*/
..此函数可被执行。
/*
+function test(){
console.log('a');
}()
*/
/*
function test (a, b, c, d) {
console.log(a + b + c + d);
}(1, 2 ,3 ,4)
*/
..此函数系统不会报错(会认为有逗号运算符存在它就是一个表达式)但是没意义;
逗号运算符 ,
var a = (2, 3);
a = 3;
先看前面的表达式如果前面要计算的话先计算,然后看后面的表达式要计算就计算;
然后把后面表达式的值返回:
JavaScript中为假的值有6个
分别是:
- undefined
- NaN
- 0
- “”
- null
- false
虽然这几个值都为假 但他们不一定都相等:
for exmple:
console.log( false == null ) // false
console.log( false == undefined ) // false
console.log( false == 0 ) // true
console.log( false == '' ) // true
console.log( false == NaN ) // false
console.log( null == undefined ) // true
console.log( null == 0 ) // false
console.log( null == '' ) // false
console.log( null == NaN ) // false
console.log( undefined == 0) // false
console.log( undefined == '') // false
console.log( undefined == NaN) // false
console.log( 0 == '' ) // true
console.log( 0 == NaN ) // false
对于 == 有以下结论:
- false除了和自身比较为 true 外, 和 0,""比较也为 true
- null 之和 undefined 比较是为 true 反过来 undefined 也仅和 null 比较为 true ,没有第二个
- 空字符串“”除了和 false 比较为 true 还有一个数字 0;