Can the bind function in js bind dynamic variables?

background: when testing a broadcast effect component, use Math.random () to generate a random number to pass to the broadcast function
the expected effect is as follows:

:


:

you can see that the number bound through bind is an immutable number.
question: how to rewrite to keep the variable number while using bind

Mar.11,2021

first you need to figure out why the number doesn't change, because Math.random () is called only once.
you can take a look at the simple implementation of bind

Function.prototype.bind = function(oThis) {
    var aArgs = Array.prototype.slice.call(arguments, 1);
    var fToBind = this;
    var fBound = function() {
        return fToBind.apply(oThis, args);
    };
    return fBound;
}

because Math.random () is passed into the update method as the second parameter of bind, the execution result of Math.random () is actually stored in the above args. The bind function returns that fBound is a function constantly called by the timer, and the value of the args variable is obtained from the external scope when fBound is executed.
if you want to change every time, just put Math.random () into the update function to execute


update should also be changed to call function

function update(n) {
   console.log(n())
}

setInterval(update.bind(null, () => Math.random()),1000)

bind is impossible bind

setInterval(() => {
    update.call(null, Math.random())
}, 1000)
Menu