node.js/javascript 语法基础笔记

来源:互联网 发布:2016年学java有前途吗 编辑:程序博客网 时间:2024/05/24 00:13

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> a5> 
复杂类型相当于pointer,新的变量和旧变量指向内容相同。

> var a = ['hello','world'];//array objectundefined> 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===bfalse> 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:3Jacquelines-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();

在内部对变量进行的改动只对内部对象生效。









0 0