javaScript-将对象作为函数参数传递 [英] javaScript - pass object as function argument

查看:105
本文介绍了javaScript-将对象作为函数参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用一个对象作为函数参数.当我在功能以外定义对象,然后将其作为参数传递时,它可以正常工作:

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?

推荐答案

ES6支持参数解构. 您可以使用:

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)
}

只有旧版IE不支持它.

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)
}

您不能以这种方式传递参数或初始化默认参数.此外,在您的情况下,this将引用父对象,因此this.arguments.a并不有意义,因为在大多数情况下,它会引用window对象.

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

尽管如此,任何不带参数调用它的尝试都会导致错误,因为JS会尝试解析undefined

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

您可以使用其他默认参数分配来解决此问题.当您确实要调用不带参数的bar()且具有解构参数的默认值时,应使用以下命令:

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} = {}){/*...*/}

别忘了它不受浏览器的广泛支持,因此您将不得不使用transpiler来转换浏览器支持的ES6代码.

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.

最受欢迎的编译器是 Babel 打字稿.

Most popular transpilers are Babel and Typescript.

这篇关于javaScript-将对象作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆