object in javascript function definition

╄→尐↘猪︶ㄣ 提交于 2019-12-08 04:46:31

问题


My friend was just making some nonesense code, or atleast I thought he was, but to my surprise it did not throw any error. It however did not do what he expected, as he didn't really know what he was doing. But now I am quite curious what it does do, because there must be some reason it doesn't throw an error. The code looked something like this:

var n = function(someArg, anotherArg, {help: []}){};

Also, when adding data into the object, it throws an error:

var n = function(someArg, anotherArg, {help: ["something"]}){};

Throws: 'Uncaught SyntaxError: Unexpected string'

so why is a random argument allowed?


回答1:


This is EcmaScript 6 argument destructuring. If you define a function as:

function myfun({help: [a, b, c]}) {}

You can then call it as:

myFun({help: [1, 2, 3]});

and it will bind the arguments a, b, and c to 1, 2, and 3 respectively. Your example is simply a degenerate case of this, where the array containing the variables is empty.

In a destructuring argument list, the places where expressions can go in an ordinary object or array literal have to contain a variable name, as that's the variable that will be bound to the corresponding element in the argument object/array. This is why the second version produced an error: "something" is not a variable name, it's a string, so it can't be used in a pattern.



来源:https://stackoverflow.com/questions/43597812/object-in-javascript-function-definition

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