简体   繁体   中英

Callback function, how to increment number from object then add to sum property

Where am i wrong? I want to increment firstNumber then I want sum result to be 2. When I tried to debug and I got error "x is not defined"

function main() {
    let object = {
        firstNumber: 1,
        sum: 0
    }
    secFun(x, object, firstFun)
    console.log(object.sum)
}

function firstFun(a) {
    a.firstNumber++;
    a.sum += a.firstFun;

}

function secFun(x, y, callback) {

    callback(x, y);
}
main();

Your main() function is calling secFun with parameter x , but you have not declared x within the function's scope.

In fact, you have not declared x anywhere.

function main() {
  let object = {
    firstNumber: 1,
    sum: 0
  }

  // 'x' is not defined in local or global scope
  secFun(x, object, firstFun)

  console.log(object.sum)
}

In additon, your secFun function calls a callback with two parameters, but firstFun accepts only one parameter.

function secFun(x, y, callback) {

    // calling 'callback' with two arguments
    callback(x, y);
}

// but firstFun accepts only one parameter
function firstFun(a) {

}

  function firstFun(a) {
    a.firstNumber++;
    a.sum += a.firstNumber;

}

function secFun(x, callback) {

    callback(x);
}
   function main() {
    let object = {
        firstNumber: 1,
        sum: 0
    }
    secFun(object, firstFun)
    console.log(object)
}

main();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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