简体   繁体   中英

Can sombody explain me this arrow function in javascript?

here is the code:

const createI18n = (config) => ({
    locale: ref(config.locale),
    messages: config.messages,
    $t(key) {
        return this.messages[this.locale.value][key]
    },
})

Is locale an object or a proprety of object?

I'm kind of new in javascript and i really struggling in understanding this arrow function.

This has nothing to do with arrow functions.

locale is the name of a property of an object.

The value of that property is another object (which has a property named value on it).

To better understand what is going on here, you could take a look at a normal function equivalent:

    function createI18n(config){
        return {
           locale: ref(config.locale),
           messages: config.messages,
           $t(key) {
              return this.messages[this.locale.value][key]
           }
        }
}

So basically you are returning an object from that arrow function. You are also using a shorthand version of an arrow function, which omitts the return keyword.

So those two are equivalent to the one above as well

const createI18n = (config) => ({
    locale: ref(config.locale),
    messages: config.messages,
    $t(key) {
        return this.messages[this.locale.value][key]
    },
})

const createI18n = (config) => {
/* you could do some operations here, but not in the shorthand version */
return {
    locale: ref(config.locale),
    messages: config.messages,
    $t(key) {
        return this.messages[this.locale.value][key]
    },
  }
}

It is just a more convenient kind to write the function.

update: The result object would look like this:

{
 locale: //some value,
 messages: //some other value,
 $t: // function
}

update 2: you could rewrite your function to observe the result in the console.

const createI18n = (config) => {
const result = {
     locale: ref(config.locale),
     messages: config.messages,
     $t(key) {
         return this.messages[this.locale.value][key]
     },
 }
 console.log(result);
 return result
}

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