简体   繁体   English

调用函数时如何传递参数名称?

[英]How do I pass in argument names when I call a function?

function go(a, b){
        console.log(a);
        console.log(b);
    }

go(b="happy", a="sad");

How can I make this work, just like it does in python? 我该如何做这项工作,就像在python中一样?

Not really part of the language, but you can fake it like this: http://www.javascriptkit.com/javatutors/namedfunction.shtml 并不是语言的真正组成部分,但是您可以像这样伪造它: http : //www.javascriptkit.com/javatutors/namedfunction.shtml

Example: 例:

function go( params ) {
    console.log(params.a);
    console.log(params.b);
}

go( { b:"happy", a:"sad"} );
go(sad, happy);

Just be sure you use the same order. 只要确保您使用相同的顺序即可。 If the function is declared as: 如果函数声明为:

function(a,b){}

Then the attributes must be a,b; 然后属性必须是a,b; not b,a. 不是b,a

Alternatively, if you really want to name them, use a colon in front of the attribute name. 另外,如果您确实要命名它们,请在属性名称前使用冒号。

While there are some libraries which claim that they will let you do that (Prototype has a backwards way of making this possible), it is not cross browser compliant and it certainly isn't the the ECMAScript specification that JS is based off of. 尽管有一些库声称可以让您做到这一点(Prototype具有向后的实现方式),但它不兼容跨浏览器,并且肯定不是JS所基于的ECMAScript规范。

The only way to have reliable behavior is to use the arguments in the order they were listed. 具有可靠行为的唯一方法是按参数的列出顺序使用它们。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM