JavaScript回调函数如何无需再次传参即可访问其他参数?
回调函数无需额外传参即可访问其他参数的示例
这其实是JavaScript里闭包特性的典型应用——回调函数不用额外传递参数,就能访问到所在作用域(或上下文)里的其他内容。
以下是对应的代码片段:
var SimplePropertyRetriever = { getPrototypeEnumerables: function(obj) { return this._getPropertyNames(obj, false, true, this._enumerable); }, _enumerable: function(obj, prop) { return obj.propertyIsEnumerable(prop); }, _getPropertyNames: function getAllPropertyNames(obj, iterateSelfBool, iteratePrototypeBool, includePropCb) { // ... 内部实现逻辑 } }
核心逻辑说明
- 你看
getPrototypeEnumerables方法调用this._getPropertyNames时,直接把this._enumerable作为回调传了进去 - 当
_getPropertyNames内部调用includePropCb(也就是_enumerable)时,_enumerable不需要额外接收其他上下文参数,就能正常执行逻辑——这是因为闭包帮它保留了对SimplePropertyRetriever这个上下文的访问,而它自身需要的obj和prop参数,会在调用时由_getPropertyNames传入 - 这种写法既保持了代码的模块化拆分,又利用闭包避免了冗余的参数传递,让整体逻辑更简洁清晰
内容的提问来源于stack exchange,提问作者Magnus
相关产品推荐
相关产品推荐

