实现说明
Function.length 统计默认值前的参数个数可以归结为函数 connect、broadcast、register、ping。
使用要点
- 演示输出是带标签的(
broadcast :、required options:),每个操作都会留下自己的一行标注。
常见问题
依赖情况复杂吗?
一点也不复杂:零依赖,没有要锁版本或审计的东西。 文件在加载时定义 connect、broadcast、register。
入口签名:function connect(url, timeoutMs = 5000)
代码示例
// Function.prototype.length counts declared parameters up to the first
// one that has a default value; rest parameters add zero. Frameworks
// read it to decide how many arguments a handler expects.
function connect(url, timeoutMs = 5000) {}
function broadcast(...channels) {}
function register(label, { retries = 0 } = {}) {}
function ping(host, port, timeoutMs) {}
console.log('connect :', connect.length); // 1
console.log('broadcast :', broadcast.length); // 0
console.log('register :', register.length); // 1
console.log('ping :', ping.length); // 3
// Making a previously required parameter optional shifts the boundary
function strict(url, options) {}
function lenient(url, options = {}) {}
console.log('required options:', strict.length, '| defaulted:', lenient.length);