简体   繁体   English

在Javascript中将函数作为参数传递时返回值

[英]Return value when passing a function as an argument in Javascript

I have some javascript code that works fine when I pass an object to a method. 当我将对象传递给方法时,我有一些javascript代码可以正常工作。 In the API documentation , it says that I can also pass a function to the method. API文档中 ,它说我还可以将一个函数传递给该方法。 When I try this, I'm able to pass parameters and do an alert to verify that the parameters are being passed. 尝试此操作时,我可以传递参数并发出警报以验证是否正在传递参数。 However, I'm not able to return the value. 但是,我无法返回该值。

What is the line of javascript that I'm missing to properly return the value? 我缺少正确返回值的javascript行是什么?

var result = {model: "todo"};

//$httpBackend.whenGET(/^\/api\//).respond(result);
$httpBackend.whenGET(/^\/api\//).respond(do_something);

function do_something(method, url, data) {
    alert("url "+url); // or whatever
    var result =  {model: "todo"};
    return result;
}

//From the API documentation
//   $httpBackend.whenGET('/.*/').respond(function(method, url, data) {
//     do something
//});

Presumably, the return value of that function is ignored. 据推测,该函数的返回值将被忽略。 Certainly it's not being used in your current code. 当然,您当前的代码中并未使用它。

You need to have that function affect a variable scoped outside of the function itself: 您需要使该函数影响该函数本身之外的作用域变量:

var result;
$httpBackend.whenGET(/^\/api\//).respond(do_something);
// Do something with `result`...
alert(result.model); // or whatever

function do_something(method, url, data) {
    alert("url "+url); // or whatever
    result =  {model: "todo"};
}

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

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