鍍金池/ 問答/HTML/ js中bind函數(shù)可以綁定動態(tài)變量嗎

js中bind函數(shù)可以綁定動態(tài)變量嗎

背景:在測試一個廣播效果組件,用Math.random()生成一個隨機數(shù)傳給廣播函數(shù)
期待的效果如下:
圖片描述
數(shù)字是隨機數(shù)

但是使用這樣的寫法:

    // update為廣播函數(shù),傳入內(nèi)容即可
    setInterval(update.bind(null,Math.random()),1000)

效果如下:
圖片描述

可以看到通過bind綁定的是一個不變的數(shù)字,
問題:怎么改寫才能在使用bind的情況下,保持可變數(shù)字

回答
編輯回答
失魂人

bind是不可能bind

setInterval(() => {
    update.call(null, Math.random())
}, 1000)
2017年11月2日 02:18
編輯回答
晚風(fēng)眠

update也要改成調(diào)用函數(shù)

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

setInterval(update.bind(null, () => Math.random()),1000)
2017年9月20日 14:27
編輯回答
初心

首先需要弄明白數(shù)字為什么不會變,因為Math.random()只被調(diào)用了一次。
可以看一下簡易的bind的實現(xiàn)

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;
}

由于Math.random()作為bind的第二個參數(shù)傳進了update方法,所以上面的args里面其實就保存了Math.random()的執(zhí)行結(jié)果。bind函數(shù)返回fBound是定時器不斷調(diào)用的函數(shù),fBound執(zhí)行的時候args變量的值都是從外部作用域里獲得的。
如果希望每次都變的話,把Math.random()放到update函數(shù)中去執(zhí)行就可以了

2017年4月26日 16:43