apply() call() bind()作用與區別

apply()、call()、bind()調用對象的一個方法,用另一個對象代替當前對象;改變函數執行的上下文,換句話說就是改變函數體內部的this的指向,實現(多重)繼承

區別:

bind()是返回的是執行上下文被改變的函數且不會立即執行,call()、apply()直接執行該函數;

call()的傳參是 call(this,param1,param2…),參數必須直接傳給函數

apply()的傳參是 apply(this,[argArray]);

bind()的傳參是bind(this,param1,param2…);

第一個參數是指定的對象,這個對象就是該函數的執行上下文

call()和apply()如果第一個參數是null或者undefine那麼this的指向就是全局變量,在瀏覽器裏就是window對象

代碼示例;

// apply()
    let obj = {};
    // 不需要參數的情況
    function test() {
        console.log(this === window);
        console.log(this === obj);
    }
    test(); // true	false
    test.apply(obj); //false	true

    // 需要傳參的
    let obj = {
        name: '飛哥'
    };
    function test(name) {
        this.name = name;
        console.log(window.name);
        console.log(obj.name);
    }

    test("高飛"); // 高飛	飛哥
    test.apply(obj, ['高飛']); // 高飛	高飛


    // call() 

    // 不需要參數的情況
    let obj = {};
    function test() {
        console.log(this === window);
        console.log(this === obj);
    }

    test(); // true	false
    test.apply(obj); //false	true

    // 需要傳參的
    let obj = {
        name: '飛哥'
    };

    function test(name) {
        this.name = name;
        console.log(window.name);
        console.log(obj.name);
    }

    test("高飛"); // 高飛	飛哥
    test.call(obj, '高飛'); // 高飛	高飛


    // bind()

    // 不需要參數的情況
    let obj = {};
    function test() {
        console.log(this === window);
        console.log(this === obj);
    }

    test(); // true	false
    test.bind(obj)(); //false	true

    // 需要傳參的
    let obj = {
        name: '飛哥'
    };

    function test(name) {
        this.name = name;
        console.log(window.name);
        console.log(obj.name);
    }

    test("高飛"); // 高飛	飛哥
    test.bind(obj, '高飛')(); // 高飛	高飛

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章