我需要一些代码的布局方面的帮助。
我可以通过function3
和function1
的参数以某种方式调用function2
吗?
我无法使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 :(得分: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);
}
答案 1 :(得分: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>
答案 2 :(得分: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() )