Overview
Variables
Functions
Function scope
Arrays
Objects
1995: started in the browser (Brendan Eich | Netscape)
1997: formalized by ECMAScript
2009: moved to the backend (node.js)
2012: moved to the client (Windows 8)
prototype(原型;标准)-based
dynamic and weakly-typed
first-class functions
C-like syntax
types(string,number,boolean,array,object,null,undefined)
declarations
app.onready = function(e){ log(f1());//right log(f2());//wrong function f1(){ } var f2 = function(){ }; }
app.onready = function(e){ log(f1("one",2,0.78,{},[])); function f1(){ debugger; } } function justDo(){...} function getSomething(){... return something;} function doWithArg(arg){ //use arg } function doWithArgs(arg1,arg2){ //use arg1 or arg2 }
var ops = { add:function addNumbers(n1,n2){ return n1 + n2; } }; var x = ops.add(3,5);//x == 8 var y = ops.addNumbers(3,5);//not valid
//Demo1:Scope var x = 2000; function someFunc(){ var y = 12; return y; } var z = x + y; //invalid use of y var z = x + someFunc();//z == 2012 //Demo2:Functions in Functions function outerFunction(n){ function innerFunction(){ return n*n; } return innerFunction(); } var x = outerFunction(4);//x == 16 //innerFunction cannot be called directly
(function(){...}());
or
(function(){...})();
大体的意思是这样的:“()”将方法括起来,表示立即执行。上面第一种写法是先调用函数,然后立即执行;第二种写法是先执行,然后调用。效果是一样的,都会执行函数,并返回函数的返回值。
//Module Pattern var mod = (function(){ var m = 2000,c = 0,d = 10,y = 2; return { getHiddenYear: function(){ return m + c + d + y; } } }()); var x = mod.getHiddenYear(); // x == 2012 (function(){ function add(n1,n2){ return n1 + n2; } function calc(n1,n2,processForCalc){ return processForCalc(n1,n2); } function executeMath(){ setOutput(calc(4,4,add)); })();
上面第一个例子,因为函数立即执行后返回了getHiddenYear方法,并把这个返回结果赋给了mod,所以mod对象就有了getHiddenYear()方法。
app.onready = function(e){ var fruit = ["apple", "orange", "banana", "strawberry", "cherry"]; var vegetables = ["carrot", "broccoli", "cauliflovd"]; fruit.push("pear"); fruit.pop();//pop pear(the last pushed) fruit = fruit.concat(vegetables);//合并多个数组 fruit = fruit.slice(0,1);//截取数组(0起始(含),1结束(不含)) fruit.splice(1,2,"melon","grape");//splice(拼接),1起始,2长度,"melon"和"grape"是替换的元素,返回被替换掉的元素 fruit = fruit.map(function(i){return i.toUpperCase()}); fruit = fruit.filter(function(i){return i[0] === "a";});//按条件筛选数组 log(fruit.every(function(i){return i[0] === "a";}));//如果每一个元素的首字母都是"a",则返回true log(fruit.some(function(i){return i[0] === "a"}));//如果有至少一个元素的首字母是"a",则返回true fruit.forEach(function(i){ }); log(fruit.sort());//sort按字母顺序排列 }
//声明方式一 var dog = {}; dog.breed = "German Shepherd"; dog.bark = function(){log("woof");}; //声明方式二 var dog = { breed:"German Shepherd", bark:function(){log("woof");} };