t41*_*ate 4 javascript function object
我想使用一个对象作为函数参数。当我在 fucntion 之外定义一个对象然后将它作为参数传递时,它工作正常:
var obj = {
a: 0
}
function foo(obj){
console.log(this.obj.a);
}
foo() //0
Run Code Online (Sandbox Code Playgroud)
但是当我直接传递一个对象时,它不起作用:
function bar({a: 0}){
console.log(this.arguments.a)
}
// Uncaught SyntaxError: Unexpected number
Run Code Online (Sandbox Code Playgroud)
一个对象似乎是一个合法的论点。我如何解决它?
v-a*_*rew 10
ES6 支持参数解构。您可以使用:
function bar({a}){
console.log(a)
}
Run Code Online (Sandbox Code Playgroud)
但是,当您有多个参数时,它通常很有用:
// 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)
}
Run Code Online (Sandbox Code Playgroud)
只有旧的 IE 不支持它。
但是当我直接传递一个对象时,它不起作用:
function bar({a: 0}){
console.log(this.arguments.a)
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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} = {}){/*...*/}
Run Code Online (Sandbox Code Playgroud)
只是不要忘记它并没有被浏览器广泛支持,因此您必须使用转译器将您的 ES6 代码转换为浏览器支持的代码。
最流行的转译器是Babel和Typescript。
因为这与传递的变量无关。不要在这里使用它。简单地做:
function bar({a = 0} = {}){
console.log(a)
}
bar({});//0
bar();//0
bar({a:10});//10
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26778 次 |
最近记录: |