Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javaScript - pass object as function argument

I want to use an object as function argument. When I define an object outside fucntion and then pass it as an argument, it works fine:

var obj = {
  a: 0
}

function foo(obj){
  console.log(this.obj.a); 
}

foo() //0

But when I pass an object directly, it doesen't work:

function bar({a: 0}){
  console.log(this.arguments.a)
}
// Uncaught SyntaxError: Unexpected number

An object doesent seem to be a legal argument. How do I fix it?

like image 888
t411tocreate Avatar asked Sep 14 '17 17:09

t411tocreate


1 Answers

ES6 supports parameters destructuring. You can use:

function bar({a}){
    console.log(a)
}

However usually it is useful when you have multiple parameters:

// you pass option to a function old way
function oldOps(option){
    var protocol = option.protocol;
    var method = option.method;
    var port = option.port;
    console.log(port);
}
// new and more readable way
function newOps({protocol, method, port}){
    console.log(port)
}

Only old IE doesn't support it.

But when I pass an object directly, it doesn't work:

function bar({a: 0}){
  console.log(this.arguments.a)
}

You cannot pass parameters this way or make initialization of a default parameter. Furthermore, this in you case will refer to the parent object, so this.arguments.a doesn't make sense as in most cases it will refer to window object.

With parameters destructuring you may use default parameters, so your code will look:

function bar({a = 0}){
    console.log(a)
}
bar({}) // 0

Still, any efforts to call it without parameter will result in error as JS will try to resolve property of undefined

You may use another default parameter assignment to resolve the issue. When you really want to call bar() without parameters and have default value for destructured parameter you should use something like:

function bar({a = 0} = {}){/*...*/}

Just don't forget that it is not widely supported by browsers, so you will have to use transpiler to convert your ES6 code one supported by browser.

Most popular transpilers are Babel and Typescript.

like image 119
v-andrew Avatar answered Oct 04 '22 20:10

v-andrew