1、JavaScript往往和html搭配使用,用法如下:
a:
<script>
//JavaScript goes here
</script>
b:
<script src="example.js"></script>
2、JavaScript没有块的概念,函数中所有的变量都为全局变量,即使是你在if、switch语句中创建的变量也是全局变量,这点与其他语言有很大不同
如:
在接下来的例子中,定义了color两次,这在别的语言中可能会引起某种错误,但在js中完全不会,但为了程序的可读性,最好不要重复定义变量
var color="blue";
if(color){
var color="purse";
console.log(color);
}
console.log(color);
其输出为:purse purse
var color="blue";
function printColor(){
var color="purse";
console.log(color);
}
printColor();
console.log(color);
其输出为:purse blue
3、创建函数时必须有关键字function
4、定义变量时不用声明类型,只需要用var声明一下
如:
var x = 3;
function numSquare(x){
return x*x;
}
var sentence ="The square of "+ x +" is equal to "+ numSquare(x);
console.log(sentence);
5、自调用函数,它们独立运行,不必调用,可以自己运行(自调用函数在jQuery中用的很多)
((function selfPrint(){
console.log("this function will automatically print this statement");
})())
6、闭包函数,可以访问自己变量,可以访问全局变量,还可以访问外部函数的变量,无需通过他传递参数
如:
function showName(firstName,lastName){
var nameInfo = " Your name is ";
function makeFullName(){
return nameInfo +firstName+" "+lastName;
}
return makeFullName();
}
console.log(showName("princess","wendy"));
输出为:Your name is princess wendy
function celebrityName(firstName){
var nameInfo="this celebrity is:";
function lastName(theLastName){
console.log( nameInfo + firstName + " " + theLastName);
}
return lastName;
}
var myName = celebrityName("wd");
myName("y");
输出为:this celebrity is:wd y
function theLocation(){
var city = "wuhan";
return{
get: function(){console.log(city);},
set: function(newCity){city=newCity;}
}
}
var myPlace = theLocation();
myPlace.get();
myPlace.set("luoyang");
myPlace.get();
输出为:wuhan
luoyang
7、匿名递归函数:
var fac = function(n){
return !(n>1)?1 : arguments.callee(n-1)*n;// arguments.callee重复调用匿名函数关键字
}
console.log(fac(3));
8、异常
var a = 100;
var b = 0;
try{
if(b == 0){
throw("divide by zero error.");
}
else
{
var c = a/b;
alert("c = "+c);
}
}
catch( e ){
alert("error:" + e);
}
finally{
alert("finally block will always execute");
}