program story

함수의 자바 스크립트 선택적 인수

inputbox 2020. 12. 3. 07:49
반응형

함수의 자바 스크립트 선택적 인수


몇 가지 매개 변수가있는 일반적인 자바 스크립트 함수가 있습니다.

my_function = function(content, options) { action }

이렇게 함수를 호출하면 :

my_function (options)

인수 "options"는 "content"로 전달됩니다.

두 인수를 모두 전달하거나 하나만 전달할 수 있도록 어떻게해야합니까? 감사합니다


단일 인수를 처리 할 매개 변수를 결정해야합니다. 당신은 모두로 취급 할 수 contentoptions.

두 가지 가능성이 있습니다.

  1. 인수의 순서를 변경하십시오. function(options, content)
  2. options정의 되었는지 확인하십시오 .

    function(content, options) {
        if(typeof options === "undefined") {
            options = content;
            content = null;
        }
        //action
    }
    

    그러나 서명을 보면 즉시 명확하지 않기 때문에 함수에 하나의 인수 만 전달하면 어떻게되는지 제대로 문서화해야합니다.


my_function = function(hash) { /* use hash.options and hash.content */ };

그리고 전화 :

my_function ({ options: options });
my_function ({ options: options, content: content });

이렇게 :

my_function (null, options) // for options only
my_function (content) // for content only
my_function (content, options) // for both

ES6 사용 :

function test(a, b = 3) {
   console.log(a, ' ', b);
}

test(1);      // Output: 1 3
test(1, 2);   // Output: 1 2

또는 어떤 유형의 콘텐츠를 받았는지 구분할 수도 있습니다. 옵션은 객체로 사용되었으며 내용은 문자열로 사용되었으므로 다음과 같이 말할 수 있습니다.

if ( typeof content === "object" ) {
  options = content;
  content = null;
}

또는 이름 변경과 혼동되는 경우보다 간단한 인수 배열을 사용할 수 있습니다.

if ( arguments.length === 1 ) {
  options = arguments[0];
  content = null;
}

이를 수행하는 두 가지 방법이 있습니다.

1)

function something(options) {
    var timeToLive = options.timeToLive || 200; // default to 200 if not set
    ...
}

2)

function something(timeToDie /*, timeToLive*/) {
    var timeToLive = arguments[1] || 200; // default to 200 if not set
    ..
}

1)에서 options필요한 속성을 가진 JS 객체입니다. 유지 관리 및 확장이 더 쉽습니다.

2)에서 함수 시그니처는 두 번째 인수가 제공 될 수 있다는 것을 읽고 이해할 수 있습니다. Mozilla 코드와 문서에서이 스타일이 사용되는 것을 보았습니다.


여기 MDN 웹 사이트 에서 ES6의 기본 매개 변수에 대한 좋은 읽기가 있습니다 .
ES6에서 이제 다음을 수행 할 수 있습니다.

secondDefaultValue = 'indirectSecondDefaultValue';

function MyObject( param1 = 'firstDefaultValue', param2 = secondDefaultValue ){
    this.first = param1;
    this.second = param2;
}

다음과 같이 사용할 수도 있습니다.

var object = new MyObject( undefined, options );

Which will set default value 'firstDefaultValue' for first param1 and your options for second param2.

Here a demonstration in a fiddle


You can pass all your optional arguments in an object as the first argument. The second argument is your callback. Now you can accept as many arguments as you want in your first argument object, and make it optional like so:

function my_func(op, cb) {
    var options = (typeof arguments[0] !== "function")? arguments[0] : {},
        callback = (typeof arguments[0] !== "function")? arguments[1] : arguments[0];

    console.log(options);
    console.log(callback);
}

If you call it without passing the options argument, it will default to an empty object:

my_func(function () {});
=> options: {}
=> callback: function() {}

If you call it with the options argument you get all your params:

my_func({param1: 'param1', param2: 'param2'}, function () {});
=> options: {param1: "param1", param2: "param2"}
=> callback: function() {}

This could obviously be tweaked to work with more arguments than two, but it get's more confusing. If you can just use an object as your first argument then you can pass an unlimited amount of arguments using that object. If you absolutely need more optional arguments (e.g. my_func(arg1, arg2, arg3, ..., arg10, fn)), then I would suggest using a library like ArgueJS. I have not personally used it, but it looks promising.


I've created a simple library for handling optional arguments with JavaScript functions, see https://github.com/ovatto/argShim. The library is developed with Node.js in mind but should be easily ported to work with e.g. browsers.

Example:

var argShim = require('argShim');
var defaultOptions = {
  myOption: 123
};

var my_function = argShim([
    {optional:'String'},
    {optional:'Object',default:defaultOptions}
  ], function(content, options) {
    console.log("content:", content, "options:", options);
  });

my_function();
my_function('str');
my_function({myOption:42});
my_function('str', {myOption:42});

Output:

content: undefined options: { myOption: 123 }
content: str options: { myOption: 123 }
content: undefined options: { myOption: 42 }
content: str options: { myOption: 42 }

The main target for the library are module interfaces where you need to be able to handle different invocations of exported module functions.


Just to kick a long-dead horse, because I've had to implement an optional argument in the middle of two or more required arguments. Use the arguments array and use the last one as the required non-optional argument.

my_function() {
  var options = arguments[argument.length - 1];
  var content = arguments.length > 1 ? arguments[0] : null;
}

You will get the un passed argument value as undefined. But in your case you have to pass at least null value in the first argument.

Or you have to change the method definition like

my_function = function(options, content) { action }

Call like this

my_function ("", options);

You could also put a check in the action like: options = !options ? content : options that sets options to the first argument if no second was passed in, and then you just set content to null (or ignore it, however you want to check that)

참고URL : https://stackoverflow.com/questions/3147640/javascript-optional-arguments-in-function

반응형