首页 > 解决方案 > 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”,因此此方法无法正常工作。任何的想法?

标签: javascriptoverwrite

解决方案


如果您返回结果,这可能很简单。

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")


推荐阅读