[英]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.