js知識點學習01

js知識點學習01

1.arguements對象

(1) 什麼是arguements對象?

由於 JavaScript 允許函數有不定數目的參數,所以需要一種機制,可以在函數體內部讀取所有參數。這就是arguments對象的由來。

(2) 怎麼使用?

arguments對象包含了函數運行時的所有參數,arguments[0]就是第一個參數,arguments[1]就是第二個參數,以此類推,不存在的爲undefined。這個對象只有在函數體內部,纔可以使用。

function fun(one) {
    console.log(arguments[0]);
    console.log(arguments[1]);
    console.log(arguments[2]);
    console.log(arguments[3]);
}
fun(0,1,2)
//0
//1
//2
//undefined

正常模式下,arguments對象可以在運行時修改。

var f = function(a, b) {
    arguments[0] = 4;
    arguments[1] = 5;
    return a + b;
}
console.log(f(2, 3) )// 9

嚴格模式下,arguments對象在運行被修改無效。

var f = function(a, b) {
    'use strict'
    arguments[0] = 4;
    arguments[1] = 5;
    return a + b;
}

console.log(f(2, 3) )// 5

argumentslength屬性

function f() {
    return arguments.length;
}

console.log(f(1,2,3,4));//4
console.log(f(1,2));//2
console.log(f());//0

(3) 與數組的關係

arguments看着像數組,其實是對象,數組的方法不能在arguments對象上直接使用。

如果想讓arguments對象使用數組方法,需要先轉換爲數組。

方法1:使用slice

function f() {
    // return arguments.length;
    var args = Array.prototype.slice.call(arguments)
    console.log(args)//[ 1, 2, 3, 4 ]
}

f(1,2,3,4);

方法2:或者遍歷使用數組的push方法

function f() {
    // return arguments.length;
    // var args = Array.prototype.slice.call(arguments)
    var args = []
    for (let i=0;i<arguments.length;i++){
        args.push(arguments[i])
    }
    console.log(args)//[ 1, 2, 3, 4 ]
}

f(1,2,3,4);//4

2. 函數的閉包

(1)定義

閉包就是能夠讀取其他函數內部變量的函數。

下面這段代碼中,f2可以讀取f1的變量,f2就可以視爲一個閉包。

function f1() {
    var n = 999;
    function f2(){
        console.log(n);
    }
    return f2()
}
f1()//999

(2)閉包的用處

閉包的兩大用處:

一是可以讀取外層函數內部的變量

二是讓這些變量始終保持在內存中,閉包使得內部變量記住上一次調用時的運算結果。

function createIncrementor(start) {
    return function (){
        return start++
    }
}
var inc = createIncrementor(5);
console.log(inc())//5
console.log(inc())//6
console.log(inc())//7
console.log(inc())//8

閉包可以封裝對象的私有屬性和私有方法

function Person(name) {
    var _age;//私有屬性
    function setAge(n){
        _age = n;
    }
    function getAge() {
        return _age
    }
    return {
        name:name,
        getAge:getAge,
        setAge:setAge
    }
}
var p1 = Person('張三');
p1.setAge(24)
console.log(p1.getAge())//24

3.立即表達式

立即表達式及立即調用的表達式,簡稱IIFE(Immediately-Invoked Function Expression)

有兩種寫法

// 寫法1
(function () {
    console.log(111)
    console.log(222)
}());
//寫法2
(function () {
    console.log(333)
    console.log(444)
})();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章