带有选项的 Javascript 对象函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8009051/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:58:47  来源:igfitidea点击:

Javascript object function with options

javascriptfunctionobjectoptionsliterals

提问by devjs11

I am trying to create a function with options. I belive i have to use objects but fail so far. By options i mean something like that:

我正在尝试创建一个带有选项的函数。我相信我必须使用对象,但到目前为止失败了。通过选项,我的意思是这样的:

insertButton({
    settings:{
        value1:'Some text'      
    }
});

function insertButton(settings){
    settings = new Object();    
    document.write(settings.value1);
}

Obviously that wont work but I am trying to show what I mean. Maybe someone could help.

显然这行不通,但我试图表明我的意思。也许有人可以帮忙。

I am asking because right now I have simple function where I can pass values with strict order. With options I want to be undependable of variables order in function. For example:

我问是因为现在我有一个简单的函数,我可以在其中以严格的顺序传递值。使用选项,我希望不依赖函数中的变量顺序。例如:

function insertButton2(value1,value2,value3){
    document.write(value1);
    document.write(value2);
    document.write(value3);   
}

insertButton2('a','','c');  //empty commas to skip value2 

Leaving empty commas to make sure 'c' is value3 is not convenient for me. That is why I would like to try objects, options.

留下空逗号以确保 'c' 是 value3 对我来说不方便。这就是为什么我想尝试对象,选项。

Thx.

谢谢。

回答by Zirak

You just pass into the function an object with the required keys/values:

您只需将具有所需键/值的对象传递给函数:

function parameterify(params) {
    console.log(params.isAwesome);
}

parameterify({
    isAwesome : true
});
//logs true

You had two mistaknes:

你有两个错误:

  1. There are no names parameters in js, so {settings:{}}would pass an object with a key of settings (so that inside of the functions, you'd have to do settings.settings)

  2. You redeclared settingsat the top of the function (settings = new Object();), which no matter what you pass in will always overwrite it. As a side note, new Objectis iffy - object literal {}is way cooler

  1. js 中没有名称参数,因此{settings:{}}会传递一个带有设置键的对象(以便在函数内部,您必须这样做settings.settings

  2. settings在函数 ( settings = new Object();)的顶部重新声明,无论您传入什么,它都将始终覆盖它。作为旁注,new Object不确定 - 对象文字{}更酷

回答by JaredMcAteer

Well you're overwriting settingsto a blank Object in the first line of your function, take that out and it will work...

好吧,您正在settings函数的第一行覆盖一个空白对象,将其取出,它将起作用...

Edit: Sorry early remove the settings object from the arguments should just be

编辑:抱歉,早点从参数中删除设置对象应该只是

insertButton({
       value1:'Some text'      
});

回答by Jan Turoň

Try this

试试这个

function insertButton(settings){
    document.write(settings.value1);
}

insertButton({
    value1:'Some text'      
});