reference: SMASHING Node.js: JavaScript Everywhere by Guillermo Rauch
1. javascript 类型:
基本类型:number, boolean, string, null, undefined
复杂类型:array, function, object
基本类型的引用相当于c++中一样,新的变量复制旧变量的数值和结构。
> var a = 5;
undefined
> var b = a;
undefined
> b = 6;
6
> a
5
>
复杂类型相当于pointer,新的变量和旧变量指向内容相同。
> var a = ['hello','world'];//array object
undefined
> var b = a;
undefined
> b[0] = 'bye';
'bye'
> a[0];
'bye'
>
创建一个变量的时候,它的类型是不确定的:
> var a = new String('woot');
undefined
> var b = 'woot';
undefined
> a==b;
true
> a===b
false
> typeof a;
'object'
> typeof b;
'string'
>
这个例子中,b是直观定义的,类型是string,而a是一个object。
最好用直观的方式定义变量。(并不知道为什么)
2. 以下在表达式中会被判断为false
null, undefined, ' ', 0
typeof null == 'object';//true, 并不会判定为类型null.
3. 函数
函数可以储存在变量中,可以像其他变量一样进行传递。
> var a = function(){};
undefined
> console.log(a);
[Function: a]
undefined
>
每个函数都可以有函数名,函数名和函数变量名是不一样的概念。
var f_var = function f_func(){
console.log("This is from function named f_func");
};
f_func();
output:
f_func();
^
ReferenceError: f_func is not defined
at Object.<anonymous> (/Users/apple/Desktop/foundation.js:4:1)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
at bootstrap_node.js:542:3
Jacquelines-MacBook-Pro:Desktop Jacqueline$
error: f_func is not defined.
如果代码是如下的话,output是正常的,也就是说只有f_var是defined,并且可以通过f_var调用函数。
var f_var = function f_func(){
console.log("This is from function named f_func");
};
f_var();
函数的参数个数被称为length(一个属性):
var a = function(a,b,c){};
console.log(a.length==3);//true
var a = 5;
function layer1(){
console.log(a);//5
a = 6;//var a = 6; (原书是写作重新声明一个新变量a,这样的结果是使a变成undefined类型,因此在这里有修改)
function layer2(){
console.log(a);//6
}
layer2();
};
layer1();
在内部对变量进行的改动只对内部对象生效。