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)
})();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章