简体   繁体   English

javaScript - 将对象作为函数参数传递

[英]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:当我在 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?我如何解决它?

ES6 supports parameters destructuring. ES6 支持参数解构。 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.只有旧的 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, 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.此外,在您的情况下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 Babel and Typescript .最流行的转译器是BabelTypescript

Cause this has 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

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 .接下来,在访问参数时,只需使用参数名称,而不是this this is used to reference the invocation context object, not function parameters. this用于引用调用上下文对象,而不是函数参数。 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 .而且,在适当的情况下,它可以指向 Global ( window ) 对象或undefined this is typically confusing for a lot of JavaScript developers. this通常会让许多 JavaScript 开发人员感到困惑。 Here's a link to more information on this .这里有一个链接,指向更多关于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

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 not passing in an object as a function argument.没有将对象作为函数参数传入。 What you are doing is declaring a variable under window (assuming this is browser code) and then logging that variable's value to the console.正在做的是在window下声明一个变量(假设这是浏览器代码),然后将该变量的值记录到控制台。 Because this is context and this is defined by the way the function is called , in this instance the context is window and so your code works.因为this上下文this是由调用函数的方式定义的,在这种情况下,上下文是window ,因此您的代码可以工作。

You second code example compounds the errors you're making in the first example.您的第二个代码示例复合了您在第一个示例中犯的错误。 arguments is scoped locally to the function. arguments在函数的本地范围内。 It doesn't need this in front of it.在它面前不需要this And you can't access it like it's an object because arguments is an array-like structure.你不能像访问它一样访问它,因为arguments是一个类似数组的结构。 You would access it like this: arguments[0].a assuming you're passing the object into your function like this: bar({a: 1}) .您可以像这样访问它: arguments[0].a假设您将对象传递给您的函数,如下所示: bar({a: 1})

JavaScript context and scope can be a very difficult concept to get your head around. JavaScript 上下文和范围可能是一个很难理解的概念。 I'm a pretty seasoned JS developer and it still catches me out occasionally, so don't be disheartened.我是一个非常有经验的 JS 开发人员,它仍然偶尔会吸引我,所以不要灰心。 This article is very good at explaining context (and function scope) and I think you would benefit from reading it. 这篇文章非常擅长解释上下文(和函数范围) ,我认为你会从阅读中受益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript:如何将对象作为参数传递给addEventListener函数? - JavaScript : How to pass object as argument to addEventListener function? 什么时候需要在javascript函数中将对象作为参数传递? - When is it necessary to pass object as argument in a function in javascript? Javascript | 将对象函数作为参数传递给另一个对象 - Javascript | Pass an objects function as argument into another object 在javascript中将对象引用作为函数参数传递 - pass object reference as function argument in javascript 在javascript中传递一个函数作为参数 - pass a function as argument in javascript 无法在 javascript 函数调用中将 JSON 对象作为第二个参数传递 - Not able to pass JSON object as second argument in javascript function call 当我将对象作为参数传递时,JavaScript抛出:“不是函数” - JavaScript throws: “is not a function” when I pass object as argument 无法从映射函数传递数组对象作为参数 javascript - Cannot pass array object from map function as argument javascript javascript/typescript - 通过 eslint 规则强制将 object 作为 function 参数传递 - javascript/typescript - force to pass object as function argument by eslint rule javascript:将对象作为参数传递给字符串内的 onclick 函数 - javascript: pass an object as the argument to a onclick function inside string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM