预解析(声明提升) JavaScript的代码在执行的过程中分为两个过程:预解析,逐行执行。预解析:声明提升,JavaScript代码在执行之前会把变量和函数的声明提升到代码的最前面,赋值部分不会提升。 // console.log(a); // undefined // var a = 10; // 上面两行代码相当于 // console.log(a); // undefined // var a; // a = 10; // js有预解析过程:把声明提升带最前面 // var a; // console.log(a); // undefined // a = 10; // 普通函数也可以预解析 // fun(); // function fun() { // console.log('fun'); // } 函数的返回值 函数可以是 return 返回结果。return的作用: 结束函数的执行返回结果到函数调用处一个函数返回一个结果,一般只有一个return(分支语句除外)函数没有return,默认返回 undefined 函数的返回值可以是任意数据类型。 获取非行间样式 // 封装获取样式函数 // ele:元素 attr:样式名(字符串) function getStyle (ele, attr) { // if (window.getComputedStyle) { // 标准浏览器 // return window.getComputedStyle(ele)[attr]; // } else { // 低版本IE // return ele.currentStyle[attr]; // } return window.getComputedStyle ? window.getComputedStyle(ele)[attr] : ele.currentStyle[attr]; } 定时器 JavaScript中的定时器分为两种:setTimeout,setInterval setTimeout setTimeout(函数, 延迟时间):延迟固定时间执行一次函数,只会执行一次。 // setTimeout(函数, 延迟时间):延迟固定时间执行一次函数,只会执行一次。 // setTimeout(function () { // console.log('timeout'); // }, 2000); function fun () { console.log('fun'); } // fun(); setTimeout(fun, 2000); setInterval setInterval(函数, 间隔时间):每间隔固定时间执行一次函数。 // setInterval(函数, 间隔时间):每间隔固定时间执行一次函数。 // setInterval(function () { // console.log(Math.random()); // }, 1000); function random () { console.log(Math.random()); } // random(); setInterval(random, 1000); 清除定时器 clearTimeout(intervalId):清除延迟器。每个定时器添加后会返回一个唯一标识符(intervalId),从1开始。clearInterval(intervalId):清除定时器 var t1 = setTimeout(function () { console.log('timeout'); }, 1000); clearTimeout(t1); var t2 = setInterval(function () { console.log('interval'); }, 1000); clearInterval(t2);