简体   繁体   中英

Why can't function access local variable in object declared outside

I was adding validation functions for my Node application, and want a custom message for the field I provide in that function. The issue is, some options need to have a default values, and others I can pass as parameters.

let field = 'email';

let options = {
  'message': `${field} is required`
}

function validation(field, opt = options) {
  console.log(opt.message);
}

validation('password');
validation('confirm', {message: 'Confirm password is required'})

But in this case, the output is

"email is required"
"Confirm password is required"

While I want the output to be

"password is required"
"Confirm password is required"

I also want to know how Javascript works for this code. How it is accessing all the stuff and how to get the required output.

Thanks

let field = 'email';

let options = {
  'message': `${field} is required`
}

This assigns options.message with the current value of field . Since you never changes its value, you get "email is required" . The parameter named field in function validation(field, opt = options) is a different variable than the global one with the same name. And its value has no affect on the value of options.message because that assignment was already executed before the function was ever called.

Manipulating global objects is considered poor programming. Instead, you can create the object inside the function:

function validation(field) {
    let opt = {
      'message': `${field} is required`
    }

      console.log(opt.message);
}

In your code you just create option object and you create it with message field = "email is required". And you never change it's value. As an alternative you may generate object each time you want it to be parametrized:

const field = 'email';

const getOptions = (field) => ({
  'message': `${field} is required`
});

function validation(field, opt) {
  opt = opt || getOptions(field);
  console.log(opt.message);
}
   message:`${field} is required`

Is the same as:

 message: field + " is required"

which directly looks up field and results in:

 message: "email is required"

To evaluate later you have to use a function that you pass the field name in which then returns the message:

 const options = {
   message: field => `${field} is required`,
 }

 function validation(field, opt = options) {
   const msg = typeof opt.message === "function" ? opt.message(field) : opt.message;
   console.log(msg);
 }

 validation('password');
 validation('confirm', {message: 'Confirm password is required'})

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