javaScript - 将对象作为函数参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46224895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javaScript - pass object as function argument
提问by t411tocreate
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:
我想使用一个对象作为函数参数。当我在 fucntion 之外定义一个对象然后将它作为参数传递时,它工作正常:
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?
一个对象似乎是一个合法的论点。我如何解决它?
回答by v-andrew
ES6 supports parameters destructuring. You can use:
ES6 支持参数解构。您可以使用:
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.
只有旧的 IE 不支持它。
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, thisin you case will refer to the parent object, so this.arguments.adoesn't make sense as in most cases it will refer to windowobject.
您不能以这种方式传递参数或初始化默认参数。此外,this在你的情况下将引用父对象,因此this.arguments.a在大多数情况下它会引用window对象是没有意义的。
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
尽管如此,任何不带参数调用它的努力都会导致错误,因为 JS 将尝试解析 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:
您可以使用另一个默认参数分配来解决该问题。当您真的想bar()不带参数调用并且具有解构参数的默认值时,您应该使用以下内容:
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.
只是不要忘记它并没有被浏览器广泛支持,因此您必须使用转译器将您的 ES6 代码转换为浏览器支持的代码。
Most popular transpilers are Babeland Typescript.
最流行的转译器是Babel和Typescript。
回答by Jonas Wilms
Cause thishas nothing todo with the variables passed. Dont use it here. Simply do:
因为这与传递的变量无关。不要在这里使用它。简单地做:
function bar({a = 0} = {}){
console.log(a)
}
bar({});//0
bar();//0
bar({a:10});//10
回答by Scott Marcus
First, it appears that you are combining how to declare a function parameter with how to call a function and pass it a parameter with this code:
首先,您似乎将如何声明函数参数与如何调用函数并使用以下代码传递参数相结合:
function bar({a: 0}){
console.log(this.arguments.a)
}
Next, when accessing arguments, just use the parameter name, not this. thisis used to reference the invocation context object, not function parameters. The invocation context object is essentially the object that was responsible for causing the function to be invoked in the first place. It can also point to an object that was explicitly set to replace the native object that would have been the context object. And, in the right circumstances, it can point to the Global (window) object or be undefined. thisis typically confusing for a lot of JavaScript developers. Here's a linkto more information on this.
接下来,在访问参数时,只需使用参数名称,而不是this. this用于引用调用上下文对象,而不是函数参数。调用上下文对象本质上是负责首先调用函数的对象。它还可以指向一个被显式设置为替换本来是上下文对象的本机对象的对象。而且,在适当的情况下,它可以指向 Global ( window) 对象或undefined. this许多 JavaScript 开发人员通常会感到困惑。这是有关更多信息的链接this。
So your code should be:
所以你的代码应该是:
// Declare the function and set up a named parameter
function bar(someObj){
console.log(someObj)
}
// Call the function and pass an object literal:
bar({a: 0});
Now, you can in fact supply a default value for a function and this would be how to do that:
现在,您实际上可以为函数提供默认值,这将是如何做到的:
// Establish an object with an `a` property with a value of "Hello"
// as the default value of the function's argument
function bar(obj = {a: "Hello"}){
console.log(obj);
}
bar(); // Default value of parameter will be used
bar({a:"Goodbye"}); // Passed value will be used
回答by Andy
None of the answers have actually tried to address the issue here so I thought I might have a go.
没有一个答案实际上试图解决这里的问题,所以我想我可以试一试。
You ask: "I want to use an object as function argument." And yet your first example doesn't show you doing this. You are notpassing in an object as a function argument. What you aredoing is declaring a variable under window(assuming this is browser code) and then logging that variable's value to the console. Becausethisis contextand thisis defined by the way the function is called, in this instance the context is windowand so your code works.
你问:“我想使用一个对象作为函数参数。” 然而,您的第一个示例并未显示您这样做。您没有将对象作为函数参数传入。您正在做的是在window(假设这是浏览器代码)下声明一个变量,然后将该变量的值记录到控制台。因为this是上下文并且this是通过调用函数的方式定义的,所以在这种情况下,上下文是上下文window,因此您的代码可以正常工作。
You second code example compounds the errors you're making in the first example. argumentsis scoped locally to the function. It doesn't need thisin front of it. And you can't access it like it's an object because argumentsis an array-like structure. You would access it like this: arguments[0].aassuming you're passing the object into your function like this: bar({a: 1}).
您的第二个代码示例复合了您在第一个示例中犯的错误。arguments局部作用域为函数。它不需要this在它面前。你不能像访问它一样访问它,因为它arguments是一个类似数组的结构。你会访问它是这样的:arguments[0].a假设你传递对象到你的函数是这样的:bar({a: 1})。
JavaScript context and scope can be a very difficult concept to get your head around. I'm a pretty seasoned JS developer and it still catches me out occasionally, so don't be disheartened. This article is very good at explaining context (and function scope)and I think you would benefit from reading it.
JavaScript 上下文和范围可能是一个很难理解的概念。我是一个非常有经验的 JS 开发人员,它仍然偶尔会吸引我,所以不要灰心。这篇文章非常擅长解释上下文(和函数范围),我认为你会从阅读中受益。

