December 28, 2023
Свойства функций
/*function multiply(a, b) {
return a * b;
}
console.log(Object.getOwnPropertyNames(multiply));
//[ 'length', 'name', 'arguments', 'caller', 'prototype' ]
*/
function myFunction(a, d) {
const type = typeof d;
console.log(type);
}
myFunction(1, 'd'); // Выведет "string" в консольсвойства не обязательных аргументов
function myFunction(a, d) { if (arguments.length > 1) { const argName = Object.keys(arguments)[1]; const argType = typeof d; console.log(argName, argType); } else { console.log("No optional argument provided."); } } myFunction(1, 'd'); // Выведет "1 string" в консоль myFunction(1); // Выведет "No optional argument provided." в консоль
function myFunction(a, b = 'default', c = 42) {
const getArgDetails = (arg) => {
const argName = arg.substring(0, arg.indexOf('=')).trim();
const argType = typeof eval(argName);
return { name: argName, type: argType };
};
const args = myFunction.toString().match(/\((.*)\)/)?.[1].split(',');
const optionalArgs = args.slice(args.length - (arguments.length - 1));
optionalArgs.forEach((arg) => {
const argDetails = getArgDetails(arg);
console.log(argDetails.name, argDetails.type);
});
}
myFunction(1); // Выведет "b string" и "c number" в консольfunction myFunction(...args) {
args.forEach((arg) => {
console.log(arg, typeof arg);
});
}
myFunction(1, 'hello', true); // Выведет в консоль:
// 1 number
// hello string
// true boolean