What the syntax in javascript? [closed]

纵饮孤独 提交于 2020-08-20 14:37:25

问题


How arguments list should be read ? What the syntax in arguments list - the one like object definition but with equality signs?

Media.configureVideo = function (session, uploadId, caption, durationms, delay, {
  audio_muted = false,
  trim_type = 0,
  source_type = 'camera',
 // ...
} = {}) {
 // ... Body of the function

PS The code from this repository https://github.com/huttarichard/instagram-private-api


回答1:


This is destructuring a function argument, with default values, plus a default value for the argument as a whole, in case it is omitted entirely

Consider normal destructuring:

{ a, b } = objectWithProps;

which is equivalent to

a = objectWithProps.a;
b = objectWithProps.b;

You can also add default values:

{ a = 5 } = objectWithPropsMaybe;

which is equivalent to

if(objectWithPropsMaybe.a === undefined) {
    a = objectWithPropsMaybe.a;
} else {
    a = 5;
}

You can also use destructuring on function arguments to create local variables inside a function:

function foo({ a, b }) {
    return a + b;
}

foo({ a: 2, b: 3 });

And the destructuring can have default values:

function foo({ a=0, b=0 }) {
    return a + b;
}

foo({ a: 2 });

Finally, the destructuring can have a fallback target in case no argument is supplied at all:

function foo({ a=0, b=0 } = {}) {
    return a + b;
}

foo();



回答2:


The code can be broken down to this snippet, which contains weird stuff only:

const sth = function ( { test = true } = {} ){ }

So thats a function expression, but it has so called default parameters , that means if you dont pass a value, e.g.

sth();

This special part fills in the value for you:

= {}

So if you dont pass a value it rather takes an empty object. Now it goes on with object destructuring, take this example:

 const {key} = {key:"value"};
 console.log(key) // "value"

So object destructuring just moves the keys as variables into the context, the upper equals:

const key = {key:"value"}.key;

So now putting it all together:

{    
   audio_muted = false,
   trim_type = 0,
   source_type = 'camera',
   // ...
} = {}

This sets the variables audio_muted and so on based on the keys with the same name in the passed object and if they're not passed the values are set.



来源:https://stackoverflow.com/questions/47101176/what-the-syntax-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!