js中call和apply的应用

124 阅读1分钟

1.找出数组中的最大元素

    // Math.max(),找出参数中的最大值
    // apply({},[]);改变this指向,参数放在数组中,会拆开来使用
    var max = Math.max(2, 4, 5, 1, 0);
    console.log(max);
    var arr = [1, 4, 2, 6, 10];
    //非严格模式下 apply应用到null和undefined上,指向window
    var biggest = Math.max.apply(null, arr);
    console.log(biggest);

2.将伪数组转换成数组

    //数组的slice方法应用
    var a = [0, 1, 2, 3, 4, 5, 6]
    var b = a.slice(); //slice()无参数 则全部切割(浅拷贝)
    console.log(b);
    var c = a.slice(2); //数组的index(从0开始),角标 [2,最后]
    console.log(c);
    var d = a.slice(1, 2); //[1,2) 开始和结尾,包前不包后
    console.log(d); //[1] 

    function fn() {
        // 将数组的slice方法(无参数,全部浅拷贝)应用到arguments上,将arguments的内容拷贝到新数组中
        var arr = Array.prototype.slice.apply(arguments);
        console.log(arr);
        //伪数组(内容+length)转换成数组 
        var arr2 = Array.prototype.slice.apply({
            0: "abc",
            length: 1
        });
        console.log(arr2); //["abc"]
    }
    fn(1, 2, 3)

3.数组追加

    //数组的push
    var arr = [100];
    var p = Array.prototype.push.apply(arr, [1, 2, 3, 4]);
    console.log(p); //5 push方法返回数组的长度,在原数组基础上追加,直接改变原数组
    console.log(arr); //(5) [100, 1, 2, 3, 4]
    var p2 = Array.prototype.push.apply(arr, [0, 6, 7]);
    console.log(p2); //8
    console.log(arr); //(8) [100, 1, 2, 3, 4, 0, 6, 7]

4.利用call和apply做继承

    //Cat 和 Dog 继承自 Animal
    function Animal(name, age, sound) {
        this.name = name;
        this.age = age;
        this.say = function() {
            console.log(name + " " + sound);
        }
    }

    function Cat(name, age, sound) {
        Animal.call(this, name, age, sound);
    }
    var cat = new Cat("小花", 3, "喵喵~");
    cat.say(); //小花 喵喵~

    function Dog() {
        Animal.apply(this, arguments);
    }
    var dog = new Dog("大黄", 2, "汪汪~");
    dog.say(); //大黄 汪汪~
    console.log(dog); //Dog {name: "大黄", age: 2, say: ƒ}

5.使用log代理console.log()

//封装一个函数log 内部打印逻辑还是由console.log()实现,目的是加入arguments方便传入参数
    function log() {
        //log方法依旧应用到console对象上(在控制台打印),用arguments传入参数
        console.log.apply(console, arguments);
    }
    log({
        name: "打印到控制台"
    });