在JavaScript中命名参数 [英] Named arguments in JavaScript
问题描述
函数myFunc(a,b,c)
{
if(a!= undefined)this.a = a;
if(b!= undefined)this.b = b;
if(c!= undefined)this.c = c;
}
我只想设定b的值,然后我可以做一些事情像这样。
myFunc(undefined,some Value for b,undefined);
但我想知道是否有办法让我可以这样做来设置值的b
myFunc(b:一些b值);
这可能是错误的,但您可能会明白我的意思。我想要指定属性的名称和值,以便我不必担心传递未定义的值。我怎么做到这一点?
也可以随意更改标题,我不知道这个问题应该被调用。
是的,传递一个对象字面值
function myFunc )
{
if(options.a!= undefined)this.a = options.a;
if(options.b!= undefined)this.b = options.b;
if(options.c!= undefined)this.c = options.c;
}
并且像这样调用$ / b>
var var1 = new myFunc({b:一些值为b});
或用于更动态,可扩展的方式(如前所述)
函数myFunc(obj)
{
for(var i in obj)
{
if(obj.hasOwnProperty (i))
{
this [i] = obj [i];
}
}
}
var func = new myFunc({b:some value for b});
console.log(func.b); //一些b的值
Say I have a function like this
function myFunc(a, b, c)
{
if(a!=undefined) this.a = a;
if(b!=undefined) this.b = b;
if(c!=undefined) this.c = c;
}
And I want to set only the value for b, then I could do something like this.
myFunc(undefined, "some Value for b", undefined);
But I was wondering if there was a way in which I could do something like this for setting the value of b
myFunc(b:"some value for b");
This is probably wrong, but you probably see what I mean. I want to specify the name of the property along with the value so that I do not have to worry about passing undefined values. How would I do this?
Also feel free to change the title, I have no idea what this question should be called.
yes, pass in an object literal
function myFunc(options)
{
if(options.a!=undefined) this.a = options.a;
if(options.b!=undefined) this.b = options.b;
if(options.c!=undefined) this.c = options.c;
}
and call like this
var var1 = new myFunc({b:"some value for b"});
or for a more dynamic, extensible way ( as mentioned)
function myFunc(obj)
{
for (var i in obj)
{
if(obj.hasOwnProperty(i))
{
this[i]=obj[i];
}
}
}
var func = new myFunc({b:"some value for b"});
console.log(func.b);//"some value for b"
这篇关于在JavaScript中命名参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!