简体   繁体   English

将全局变量绑定但不将“ this”绑定到回调函数

[英]Bind global variable but no 'this' to a callback function

Here is an example. 这是一个例子。 I know it doesn't work because bind() just bind the arguments of a function. 我知道这是行不通的,因为bind()只是绑定函数的参数。

global_var = 2
var foo = function(){
  console.log(global_var)
}
var bar = foo.bind(null,/* global_var =*/ 3)
setTimeout(bar)

In my case, foo is from a library so it cannot be modified (not understand why it use global scope), that's why I cannot bind a scope "this" to the function. 在我的情况下,foo来自库,因此无法进行修改(不理解为什么使用全局范围),这就是为什么我无法将范围“ this”绑定到函数的原因。

bar is going to be a callback, and I want to make sure that it can output '3' every time. bar将是一个回调,我想确保它每次都能输出“ 3”。

You can always extend your global function. 您始终可以扩展全局功能。 Check the below code snippet. 检查以下代码段。

Hope this helps you! 希望这对您有所帮助!

 var global = 2; //your global library variable var foo = function() { console.log('inside foo library'); }; //make the global function extended foo = (function(oldFn) { function newFoo() { oldFn(); console.log('inside extended function') return 3; } return newFoo; })(foo); //callback variable var bar = foo; console.log(bar()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM