问题描述
我是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")
,
也许这是您实际上正在尝试做的事情:
function reset(func){
// return a new function which overwrites what is passed in
return function(){
func("gud")
}
}
var a = reset(alert)
var b = reset(console.log)
a("alert: bad")
b("console.log: bad")