繁体   English   中英

带有两个不同函数的参数的调用函数

[英]call function with parameters of two different functions

我有两个获取参数的不同函数:

push.on('registration', function(data) {
        var id = data.registrationId;
        });


push.on('notification', function (data) {
        var count = data.count;
        });

现在,我想使用变量id并在另一个新函数中计数:

function three(id, count){

var _id = id;
var _count = count;

}

那怎么可能?

var id, count;

push.on('registration', function(data) {
    id = data.registrationId;
});


push.on('notification', function (data) {
    count = data.count;
});

现在,您可以调用three(id, count) 问题是您必须等到两个值都出现后才能调用three 可能您正在寻找符合以下条件的东西:

var id, count;

push.on('registration', function(data) {
    id = data.registrationId;
    callThree();
});


push.on('notification', function (data) {
    count = data.count;
    callThree()
});

function callThree() {
    if (id && count) {
        three(id, count);
    }
}
push.on('registration', function(data) {
    var id = data.registrationId;
    push.on('notification', function (data) {
        var count = data.count;
        three(id,count)
    });

 });

基于注释的更新:假设事件的顺序,

如果不确定事件的发生顺序,则可能需要获取id并在事件的函数范围之外进行count ,然后,当一个push函数触发时,检查另一个是否具有,如果是,则调用您的three(id, count) 一种方法是只在函数外部声明变量,然后相应地更新其值。

var id = null;
var count = null;

push.on('registration', function(data) {
        id = data.registrationId;
        count !== null ? three(id, count) : null
        });


push.on('notification', function (data) {
        count = data.count;
        id !== null ? three(id, count) : null
        });

之所以不能在函数three()中使用'id'和'count'变量,是因为它们是在各个函数的范围内声明的。 要在函数three()中使用它们,只需将其移至更高的范围。

这是我如何解决您的问题:

var id, count;

function one() {
    push.on('registration', function(data) {
         id = data.registrationId;
    });
}

function two() {
    push.on('notification', function (data) {
        count = data.count;
    });
}

function three(){
    var _id = id;
    var _count = count;
}

暂无
暂无

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

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