事件監(jiān)聽
element.addEventListener(*event*, *function*, *useCapture*)
event click等方法
useCapture
true - 事件句柄在捕獲階段執(zhí)行
false- false- 默認。事件句柄在冒泡階段執(zhí)行
實例demo
實參,形參
函數(shù)參數(shù)包括形參,實參,形參就是函數(shù)定義時的參數(shù);實參就是函數(shù)調(diào)用時傳入的參數(shù)。由于js是弱類型語言,所以js函數(shù)的形參不指定類型。
get(3,4,5,6);
function get(x,y,z) {
console.log(arguments); //[3, 4, 5, 6]獲取實參對象是個數(shù)組,是實參對象的引用
console.log(x+y+z); //12
}
var fact = function(x) {
if (x <= 1) {
return 1;
} else {
return arguments.callee(x - 1) * x;
}
};
fact(5); //120
階乘 PS:實參對象有兩個特殊屬性callee和caller,其中callee屬性代指當(dāng)前正在執(zhí)行的函數(shù),caller屬性代指調(diào)用當(dāng)前正在執(zhí)行的函數(shù)的函數(shù),caller屬性不是標準屬性,不是所有瀏覽器都支持。
函數(shù)作用域
var scope = "outter";
! function() {
console.log(scope); //undefined
var scope = "inner";
console.log(scope); //inner
}();
console.log(scope); //outter
說明:undefined 由于函數(shù)作用域的聲明提前特性,這里的scope已經(jīng)在函數(shù)頂部聲明,但是沒有被賦值,所以scope值為undefined
立即執(zhí)行函數(shù)
- 寫法如下
(function() {
console.log("1");
}()); //推薦
(function() {
console.log("2");
})();
! function() {
console.log("3");
}();
void function() {
console.log("4");
}();
~ function() {
console.log("5");
}();
作用 1.保存參數(shù)上下文環(huán)境;2.作為命名空間。
- 列子 循環(huán)中執(zhí)行異步函數(shù),并且函數(shù)參數(shù)隨循環(huán)變化
for (var i = 0; i < 10; i++) {
$.post(url, { index: i }, function() {});
} //for運行完 在執(zhí)行post 全是i=10
for (var i = 0; i < 10; i++) {
(function(index) { $.post(url, { index: index }, function() {}); }(i));
} //true