[英]Passing function by variables
I've this situation: 我有这种情况:
<script>
var cb;
function doSomething(c) {
cb = c();
}
cb();
</script>
But it doesn't work. 但这是行不通的。 I want to set a variable as function, to make a callback called by other functions.. Some ideas? 我想将变量设置为函数,以进行其他函数调用的回调。
c()
executes the function and returns a value, you need to pass a reference to it: c()
执行该函数并返回一个值,您需要传递对其的引用:
cb = c
Also, you should call the function doSomething(func)
to make the assignment. 同样,您应该调用函数doSomething(func)
进行分配。
doSomething(function(){ alert('hello'); });
cb(); // "Hello"
But if what you want is a callback then you don't need a global variable: 但是,如果您要的是回调,则不需要全局变量:
function doSomething(callback) {
// do something
if (callback) callback();
}
When you run the function with another function as parameter the callback will run. 当您使用另一个函数作为参数运行该函数时,将运行回调。
You need to assign cb first with your function: 您需要先使用功能分配cb:
<script>
var cb;
function doSomething(c) {
cb = c;
}
var myFunc = function(){
window.alert("test");
}
doSomething(myFunc);
cb();
</script>
And if you do cb=c();
如果执行cb=c();
you will execute function c
instantly and return the value to cb
if you want the variable cb
as the result of c
, do like this. 您将立即执行函数c
,如果要将变量cb
作为c
的结果,则将值返回给cb
,请执行以下操作。 otherwise, assign without running it. 否则,分配而不运行它。
You have 3 options to set a variable to a functiion 您有3个选项可将变量设置为函数
var fn = functionname;
var fn = function(param){};
this will be an anonymous function 这将是一个匿名函数 var fn = function FunctionName(param){};
this will be a named function, comes in handy when debugging, since it will present you with a function name ( console.log(c);
这将是一个命名函数,在调试时会派上用场,因为它将为您提供一个函数名( console.log(c);
You cann call it like var returnVal = fn();
您不能像var returnVal = fn();
这样称呼它var returnVal = fn();
or pass it to a function var returnVal = myFunc(fn);
或将其传递给函数var returnVal = myFunc(fn);
where myFunc calls the param, let it be inFn
it like inFn();
其中myFunc的调用帕拉姆,让它成为inFn
它像inFn();
What might be interesting to note: Since such a function is related to the global context, you can bind an object to it alter its scope. 可能需要注意的是:由于此类函数与全局上下文有关,因此可以将对象绑定到它以更改其范围。 That gives you the possibility of this
referencing the bound object. 这使你的可能性this
引用绑定的对象。 (Be aware, bind is not supported by all browsers as it is defined ECMAScript 5 , but there are quite some polyfills out there.) (请注意,由于绑定浏览器定义为ECMAScript 5 ,因此并非所有浏览器都支持bind,但是其中存在很多polyfill。)
fn.bind(object);
Or call it in another context with fn.call(object, param1, param2)
or fn.apply(object, [param1, param2])
. 或使用fn.call(object, param1, param2)
或fn.apply(object, [param1, param2])
在另一个上下文中调用它。 Nice write up on this Link to odetocode.com/blog . 好的,在此链接上写到odetocode.com/blog 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.