javascript - JavaScript:重新定义链接到函数参数的对象
问题描述
我是 JavaScript 新手,我一直坚持这一点。我从没想过这是一个问题,但我在这里。这是我的代码:
a = alert
b = console.log
function reset(func, cb){
//Here I'm just redefining "func" which is a local argument
//The question is how can I redefine the function this argument is referencing?
func = function(){
cb("gud")
}
}
reset(a, alert)
reset(b, console.log)
a("alert: bad")
b("console.log: bad")
我希望 alert 和 console.log 都被我的新函数覆盖。应该等于 alert("gud") 和 console.log("gud")。我尝试对其进行评估,它适用于警报,但由于 console.log 的名称只是“log”,因此此方法无法正常工作。任何的想法?
解决方案
如果您返回结果,这可能很简单。
let a = alert
let b = console.log
function reset(cb){
//Here i'm just redefining "func" wich is a local argument
//The question is how can I redefine the function this argument is referencing?
return function(){
cb("gud")
}
}
a = reset(alert)
b = reset(console.log)
a("alert: bad")
b("console.log: bad")
推荐阅读
- jquery - @viewchildren vs jquery 。有什么区别?
- html - 将 svg 标签转换为图像中的嵌入 svg
- google-apps-script - 查找从单个连接列(不是单元格范围)达到总和的行
- python - 如何在 Elasticsearch 中批量插入,忽略过程中可能发生的所有错误?
- c# - WPF - 尝试在按钮中创建图像,但在应用程序运行时显示的图像比在 VS2019 IDE 中小
- python - 使用 Pandas 在 Jupyter Notebook 中过滤 Excel 文档数据
- sql - 动态创建水平扩展表而不是许多连接以提高性能
- ios - Obj-C - 用多个对象过滤 NSMutableArray?
- c# - 为什么我的密码散列函数使用相同的盐产生不同的散列?
- css - 允许手机手指滚动