简体   繁体   English

作为返回匿名对象的参数的函数

[英]Function as a Parameter that Returns an Anonymous Object

I see a lot of javascript code that passes a function as a parameter that returns an anonymous object. 我看到很多javascript代码将函数作为返回匿名对象的参数传递。

myFunction(function() {
    return {
       foo: 'bar'
    };
});

What is the advantage or the purpose of using this instead of simply passing directly an anonymous object? 使用它的优点或目的是什么,而不是简单地直接传递匿名对象?

myFunction({
    foo: 'bar'
});

The difference is that if you alter the argument passed in your second code snippet, there is no way to get the original argument again. 不同之处在于,如果更改第二个代码段中传递的参数,则无法再次获取原始参数。
If you pass an function instead you can call the function more than once and get always the same argument back. 如果你传递一个函数,你可以多次调用该函数并返回相同的参数。 (if the function is implemented this way) (如果以这种方式实现该功能)

Furthermore if you use a function you can do additional stuff like logging how often your function / argument was called or so on. 此外,如果您使用函数,您可以执行其他操作,例如记录调用函数/参数的频率等等。 So using a function adds more flexibility for the user of the function. 因此,使用函数可为函数用户增加更多灵活性。
For the developer of the function on the other hand accepting a function as argument can cause the tiny problem that a function doesn´t have to return the same value every time you call it - myFunc() == myFunc() COULD return false, therefore i would not recommend handing over a function if it is supposed to JUST return an argument. 另一方面,对于函数的开发人员来说,接受函数作为参数可能会导致每次调用函数时函数不必返回相同值的微小问题 - myFunc() == myFunc() COULD返回false,因此我不建议移交一个函数,如果它应该只是返回一个参数。

Backbone uses have a lot of places where they will initialize the function if passed to get the value, eg. Backbone使用很多地方,如果传递得到值,他们将初始化函数,例如。

 Backbone.Model.extend({
     url: function() { return 'myurl.aspx'; }
 });
 // VS
 Backbone.Model.extend({
     url: 'myurl.aspx'
 });

This is clever if you will have to make some calculation / run some conditions before you'ill know that the url is. 如果您在知道网址之前必须进行一些计算/运行某些条件,这是很聪明的。

 Backbone.Model.extend({
     url: function() { 
         if ( this.get('name') ) {
             return 'service1.aspx';
         }
         else {
             return 'service2.aspx';
         }
     }
 });

Your first example sends an anonymous function as the first argument to myFunction while the second example sends an object as the first argument. 您的第一个示例发送匿名函数作为myFunction的第一个参数,而第二个示例发送一个对象作为第一个参数。

myFunction(function() {
    return {
       foo: 'bar'
    };
}); // function() {...}

myFunction({
    foo: 'bar'
}); // {foo: 'bar'}

function myFunction(what) {
    console.log(what);
}

If you are talking about closures, the main difference is that you can have private variables inside closures: 如果你在谈论闭包,主要的区别是你可以在闭包中有私有变量:

var setGet = (function() {
    var v = null;
    return {
        get: function() { return v; },
        get: function(val) { v=val; }, 
    };
});
// VS:
var setGet = {
    v: null,
    get: function() { return this.v; },
    get: function(val) { this.v; }, 
};

In the first example you can't access the variable v without using .get / .set on setGet while in the 2. example i can simple change it by setting setGet.v = 'new_val'; 在第一个例子中,你不能在setGet上使用.get / .set来访问变量v ,而在2.例子中我可以通过设置setGet.v = 'new_val';来简单地改变它setGet.v = 'new_val';

I think, it really depends where you saw the code being used. 我认为,这真的取决于你看到使用的代码。

In this case, myFunction seems to require you to pass a function rather than an Object. 在这种情况下, myFunction似乎要求您传递函数而不是Object。

But in general, Consider this 但总的来说,考虑一下

myFunction(function() {

    var a = "bar";

    return {
       foo: a
    };
});

and this: 还有这个:

var a = "bar"

myFunction({
    foo: a
});

In the second case, anyone outside is able to access a . 在第二种情况下,外部的任何人能够访问 But in first case, a becomes similar to a private variable which is exposed as public by the function. 但在第一种情况下,a变得类似于由函数公开为公共的私有变量。 So you might observe this in places where people wish to follow OOP concepts in the otherwise classless JS. 因此,您可能会在人们希望在无类JS中遵循OOP概念的地方观察到这一点。


Another case is where you require a callback function or some function that is to be called later. 另一种情况是需要回调函数或稍后要调用的函数。 So if the data is to be preserved until a certain something is over you can make it available as the return value of a function, rather than storing it globally... 因此,如果要保留数据直到某个事物结束,您可以将其作为函数的返回值使用,而不是全局存储...

In the first example You are passing a callback function. 在第一个示例中,您正在传递回调函数。

When we pass a callback function as an argument to another function,
we are only passing the function definition. We are not executing the function
in the parameter.

And since the containing function has the callback function in its parameter as a function definition, it can execute the callback anytime. This allows us to execute the callback functions at any point in the containing function.

A simple example for this is jQuery click binding : 一个简单的例子是jQuery点击绑定:

/The anonymous function is not being executed there in the parameter. 
//The anonymous function is a callback function
$("#btn_1").click(function() {
    alert("Btn 1 Clicked");
});

But in the second example you are simply passing an object to the called function. 但在第二个例子中,您只是将一个对象传递给被调用的函数。

Use this link to get more details about Callback functions. 使用此链接可获取有关回调函数的更多详细信息。 Enjoy :) 请享用 :)

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

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