简体   繁体   中英

Passing unexpected parameters to a callback function

I'm wondering if there is a way to pass an additional parameter to a callback function besides what the parent function passes it

function wrapper() {
    function functionForPassing() {
        console.log('carrot');
    }

    function test(a, b, cb) {
        cb(a,b);
    }

    test('apple', 'banana', function(first, second, passedFunction=functionForPassing) {
        console.log(first);
        console.log(second);
        passedFunction();
    });
}

You can do it using rest parameter, but callback must go first. Example:

function wrapper() {
    function functionForPassing() {
        console.log('carrot');
    }

    function test(cb, ...params) {
        cb(...params);
    }

    test(function(...other) {
        let [first, second] = other; // Destructuring assignment
        console.log(first);
        console.log(second);
    }, 'apple', 'banana', 'any', 'number', 'of', 'arguments');
}
function wrapper() {
    function functionForPassing() {
        console.log('carrot');
    }

    function test(a, b, cb) {
        cb(a, b);
    }

    test('apple', 'banana', function(first, second, passedFunction) {
        passedFunction = passedFunction || functionForPassing;
        console.log(first);
        console.log(second);
        passedFunction();
    });
}

wrapper();

The tiered scoping of js handles this for me, without having to pass the the object I am trying to access as a parameter to the callback

function wrapper() {
    var other = "carrot"

    function test(a, b, cb) {
        cb(a,b);
    }

    test('apple', 'banana', function(first, second) {
        console.log(first);
        console.log(second);
        console.log(other);
    });
}
wrapper();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM