Javascript函数的模板,带有作为对象传递的可选和必需参数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Javascript函数的模板,带有作为对象传递的可选和必需参数相关的知识,希望对你有一定的参考价值。
A simple template for a javascript function which allows for an arbitrary number of named arguments to be passed in. This is achieved by passing a single object as an argument with each of the 'real' arguments being a key/value pair. In this way arguments can be passed in any order and we can easily add in new arguments.To call, simply pass in an object with the required arguments:
myFunction ({opt1: 'cat', opt4: 'dog', opt2: 'monkey'})
Validates clean in jsLint.
function myFunction(options) { // options may contain: opt1, opt2, opt3, opt4 'use strict'; // Where a mandatory parameter is missing, throw an error if (typeof options !== 'object' || options.opt1 === undefined || options.opt2 === undefined) { throw {name: 'Error', message: 'Missing options property: opt1 and opt2 must be provided'}; } // Where an optional parameter is missing, set it to the default value var key, default_options = { opt3 : 'dog', opt4 : 99 }; for (key in default_options) { if (default_options.hasOwnProperty(key)) { if (options[key] === undefined) { options[key] = default_options[key]; } } } // All arguments are now available in the format options.opt1, options.opt2, etc // Rest of function... }
以上是关于Javascript函数的模板,带有作为对象传递的可选和必需参数的主要内容,如果未能解决你的问题,请参考以下文章