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.
fooin the first example. Sothis.objcannot actually refer to the parameterobj. Usefunction foo(){ console.log(this.obj.a); }(note: no parameter) in the first example and you'll that it still works the same. Sothis.objhas nothing to do with the parameterobj. You need to do two things: Learn more about functions and learn howthisworks.