简体   繁体   English

参数如何传递给匿名回调函数?

[英]How are arguments passed to anonymous callback functions?

I am learning AngularJS and have copied code this basic code from a tutorial (simplified/pseudo code to only include the parts relevant to this question). 我正在学习AngularJS,并已从教程中复制了该基本代码的代码(简化/伪代码仅包含与此问题相关的部分)。
The code works for me, but I am trying to better understand how the argument is being passed the the callback in the success method. 该代码对我有用,但是我试图更好地了解如何在success方法中将参数传递给回调。

// jobService object
var jobService = {         
        get : function() {
         return $http.get( 'some/api/url' );
        }
    };

jobService.get().success(function (data) {
        $scope.jobs = data;
    });

My question is, knowing that "normally" arguments are specifically passed into the functions when invoked ie: 我的问题是,知道“正常”参数是在调用时专门传递给函数的,即:

function foo(arg1) {
     alert(arg1); //alerts Hello!
};

foo('hello!');

How is the data argument being passed into the anonymous callback function? data参数如何传递到匿名回调函数中? is it: 是吗:

  • Being "injected" by AngularJS? 被AngularJS“注入”了吗?
  • Does the javascript engine simply use variables on the local scope called data ? JavaScript引擎是否只是在称为data的本地范围内使用变量?
  • does the javascript engine look for a data property on the parent object if the success method? 如果success方法,javascript引擎会在父对象上查找data属性吗?

TL;DR TL; DR

We're just defining that anonymous function, not calling it! 我们只是在定义该匿名函数,而不是调用它!

Thus data is a function parameter, not a function argument. 因此, data是函数参数,而不是函数参数。


Long version 长版

Let's take this into little pieces. 让我们把它分成小块。

success() is a function. success()是一个函数。 It's chain-called after jobService.get() . jobService.get()之后被称为链。 So, whatever the jobService.get() call returns, we're calling the success function of that object (say returnedObject.success() ). 因此,无论jobService.get()调用返回什么,我们都在调用该对象的成功函数(例如jobService.get() returnedObject.success() )。

Back to success() itself. 回到success()本身。 It can easily read other properties of its object ( returnObject from the example above). 它可以轻松读取其对象的其他属性(上例中的returnObject )。 Since we're passing in the anonymous callback function as an argument, success can easily do something like (narrowing it down to basic JS): 由于我们将匿名回调函数作为参数传递,因此success可以轻松地执行以下操作(将其范围缩小至基本JS):

function success(callback) {
    var whatever = "I'm passing this to the callback function";
    callback(whatever);
}

which would actually call our anonymous function we passed in, and assign it whatever as data ( don't forget we're just defining that anonymous function, not calling it! ) . 这实际上会调用我们的匿名函数中,我们通过了,并指定whateverdata不要忘记,我们只是定义一个匿名函数,不是要求它!)。 This makes data a function parameter, and it is basically a custom name that you use to represent and access what the success function passes into its callback function. 这使data成为函数参数,并且基本上是一个自定义名称,用于表示和访问success函数传递给其回调函数的内容。 You can use whatever you want there - this would still work perfectly fine: 您可以在那里使用任何内容-仍然可以正常工作:

jobService.get().success(function (somethingElse) {
    $scope.jobs = somethingElse;
});

Hope I didn't make this too complicated. 希望我不要太复杂。 I was trying to explain it step-by-step from the plain JS standpoint because you can easily read Angular's source to see what it does, so I thought you needed this simpler explanation. 我试图从简单的JS角度逐步解释它,因为您可以轻松阅读Angular的源代码以了解它的作用,因此我认为您需要这个简单的解释。


Here's a basic example replicating what's going on there (inspect the JS source, see how the output is the same in all three cases): 这是一个复制那里发生的事情的基本示例(检查JS源,查看在所有三种情况下输出如何相同):

 var debug = document.getElementById('debug'); function success(callback) { var whatever = 'hello world'; debug.innerHTML += '<br>success function called, setting parameter to <span>' + whatever + '</span><br>'; callback(whatever); } function callbackFunction(someParameter) { debug.innerHTML += '<br>callbackFunction called with parameter <span>' + someParameter + '</span><br>'; } success(callbackFunction); // anon function success(function(val) { debug.innerHTML += '<br>anonymous callback function called with parameter <span>' + val + '</span><br>'; }) // anon function 2 success(function(anotherVal) { debug.innerHTML += '<br>second anonymous callback function called with parameter <span>' + anotherVal + '</span><br>'; }) 
 span { color: green; } 
 <div id="debug"></div> 

An example using an object, similar to what is done in your original code: 使用对象的示例,与原始代码中的操作类似:

 var debug = document.getElementById('debug'); var myObject = { whatever: 'hello world', success: function(callback) { debug.innerHTML += '<br>success function called, fetching object property and setting the parameter to <span>' + this.whatever + '</span><br>'; callback(this.whatever); }, modifyMe: function() { debug.innerHTML += '<br>object property modified<br>'; this.whatever = 'another world'; return this; // this is crucial for chaining } } // anon function callback myObject.success(function(val) { debug.innerHTML += '<br>anonymous callback function called with parameter <span>' + val + '</span><br>'; }) debug.innerHTML += '<br><hr>'; // chaining - calling a success function on a modified object myObject.modifyMe().success(function(val) { debug.innerHTML += '<br>anonymous callback function called with modified parameter <span>' + val + '</span><br>'; }) 
 span { color: green; } 
 <div id="debug"></div> 

Here's the relevant part in the source code: 这是源代码中的相关部分:

 promise.success = function(fn) {
        promise.then(function(response) {
          fn(response.data, response.status, response.headers, config);
        });

        return promise;
 };

Read more on GITHUB . 阅读更多关于GITHUB

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

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