call()和apply()用法和两者区别

     // 1.每个函数都包含两个非继承而来的方法call()和apply().
         // 2.相同点:call()和apply()的作用都一样:改变this的指向

         // call()的用法:
        window.color = 'pink'
        document.color = 'red'
        var C = {
            color: 'blue'
        }
        function f1() {
            console.log(this.color);
        }
        f1.call() // 默认指向window
        f1.call(window)//pink
        f1.call(document)//red
        f1.call(C)//blue

        var pet = {
            words: '...',
            speak: function (say) {
                console.log(say + '' + this.words);
            },
        }
        pet.speak("陈")
        var s = {
            words: '斌'
        }
        pet.speak.call(s, '陈')

         // apply的用法
        function pet2(words) {
            this.words = words
            this.speak = function () {
                console.log(this.words);
            }
        }
        function dog(words) {
            pet2.call(this, words) // 陈
            pet2.apply(this, arguments)// 陈
        }
        //    console.log(window);
        var Dog = new dog('陈')
        Dog.speak()

         //    call和apply不同点
         // 1.传递的参数不同
        // call和apply传递的第一个参数相同都是this的指向作用域,call传递的第二个参数需要一一列举出来,而apply第二个参数是一个数组
        function add(c, d) {
            console.log(this.a + this.b + c + d);
        }
        var s = { a: 1, b: 2 }
        add.call(s, 5, 6) //14
        add.apply(s, [7, 8]) // 18

         // apply的巧妙用处:
        // apply的第二个参数是一个数组,但是程序处理的时候是将这个数组转换成了参数列表例如[1,2,3,4]--->(1,2,3,4)
        // 例子1:
         // 当我们需要在一个数组中获取最大的或者最小的值时,可以直接使用apply()方法
        var arr = [1, 2, 34, 6, 57, 43]
        console.log(Math.max.apply(null, arr));// 57
        console.log(Math.min.apply(null, arr));// 1
        // 这块在调用的时候第一个参数给了一个null,这个是因为没有对象去调用这个方法,我只需要用这个方法帮我运算,得到返回的结果就行,.所以直接传递了一个null过去
         // 例子2:
        // Array prototype.push(),在数组的的末尾添加元素
        var arr1 = [1,2,3]
        var arr2 = ["a","b","c"]
        
        arr1.push(4) 
        console.log(arr1); //[1, 2, 3, 4]
        
        Array.prototype.push.apply(arr1, arr2) //此时会将arr2数组转换成参数列表('a','b','c')
        console.log(arr1); //[1, 2, 3, 6, "a", "b", "c"]

猜你喜欢

转载自www.cnblogs.com/1825224252qq/p/11774621.html