js注意點

事件監(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
   }

arguments對象的callee的屬性

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容