繁体   English   中英

将意外参数传递给回调函数

[英]Passing unexpected parameters to a callback function

我想知道是否有一种方法可以将父函数传递的参数以外的其他参数传递给回调函数

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();
    });
}

您可以使用rest参数来执行此操作,但必须先执行回调。 例:

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();

js的分层作用域为我处理了此问题,而不必将我尝试访问的对象作为参数传递给回调

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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