2016-12-01 87 views
-1

我需要某些代碼的佈局幫助。 我可以撥打function3來自function1function2的參數嗎? 我不能讓function2成爲嵌套函數,因爲它是由onclick激活的。使用來自兩個不同函數的參數調用函數

謝謝!

function 1(){ 
//This function activates when a file is imported and calculates one variable from an imported document. 
} 
function 2(){ 
//The function activates from an "onclick()" this function calculates another variable. 
} 
function 3(){ 
//calculation of the two variables 
} 

回答

0

您可以在常用函數的作用域中創建兩個變量並檢查它們。例如:

var firstVar = null; 
var secondVar = null; 

function fnc1(){ 
//This function activates when a file is imported and calculates one variable from an imported document. 
    firstVar = importedVariable; 
    if(secVar){ 
     fnc3(); 
    } 
} 
function fnc2(){ 
//The function activates from an "onclick()" this function calculates another variable. 
    secondVar = anotherVariable; 
    if(firstVar){ 
     fnc3(); 
    } 

} 
function fnc3(){ 
//calculation of the two variables 
    alert(firstVar + secondVar); 
} 
+0

的事情是我想調用函數FC3用兩個參數。一個來自fnc1,一個來自fnc2。我知道這是不可能與我目前的代碼,但我不知道如何解決它。希望這使得sens –

0

您可以使用Promise API來處理異步函數。

此外,您無法命名以數字開頭的函數。

const element = document.querySelector('#click') 
 

 
function one(arg) { 
 
    return new Promise((resolve, reject) => { 
 
    // get the file and pass the resolve function to it 
 
    getTheFile(resolve) 
 
    }) 
 
} 
 
function two(arg) { 
 
    return new Promise((resolve, reject) => { 
 
    // bind your event inside the promise 
 
    element.addEventListener('click', e => {   
 
     resolve(arg) 
 
     console.log('click resolved') 
 
    }, false) 
 
    }) 
 
} 
 

 
// callback when promises are resolved 
 
function three([arg1, arg2]) { 
 
    console.log('calc resolved', arg1 + arg2) 
 
} 
 

 

 
Promise.all([ 
 
    one(1), 
 
    two(2) 
 
]).then(three) 
 

 
// ignore this 
 
function getTheFile(resolve) { 
 
    // get the file asynchronously 
 
    setTimeout(() => { 
 
    // get something from the file and pass it to resolve 
 
    resolve(1) 
 
    console.log('file resolved') 
 
    }, 250) 
 
}
<button id="click">Click</button>

+0

謝謝我將看看api。那些不是真正的名字只是地方hoolders :) –

+0

@williamganrot它現在的作品 – synthet1c

0
function Handler() { 
    this.foo = function(v) { this.a = v } 
    this.bar = function(v) { this.b = v } 
    this.baz = function() { return this.a + this.b } 
} 

h1 = new Handler() 
h2 = new Handler() 
h3 = new Handler() 

h1.foo(5) 
h1.bar(6) 

h2.foo(1) 
h2.bar(2) 

h3.foo(10) 
h3.bar(20) 

print(h1.baz()) 
print(h2.baz()) 
print(h3.baz()) 
相關問題