【问题标题】:Do the parameters passed into an anonymous function in Javascript have special properties?Javascript中传递给匿名函数的参数是否具有特殊属性?
【发布时间】:2014-07-27 19:48:46
【问题描述】:

我在各种博客文章中看到过这样编写的 Javascript 的 sn-ps,但我很难理解参数在传递到匿名函数时所具有的属性的概念。

对于下面给出的示例:

var http = {
    bananas: function(context) {
        var object = {
            saySomething: function (msg) {
                console.log(msg);
            }
        };
        return context(object);
    }
}

http.bananas(function (something) {
    something.saySomething("I like bananas!");
});

I like bananas!”是从这里返回的,但我不明白为什么香蕉匿名函数中的“context”参数可以这样做:

return context(object);

参数传递给匿名函数时是否有特殊属性?

如果我像这样向香蕉函数添加一个额外的参数怎么办:

bananas: function(context,string){........}

然后试试这个:

return string(object);

我得到一个错误?

【问题讨论】:

  • 查找有关“高阶函数”的信息,并了解函数对象和函数调用之间的区别。
  • context 应该是一个函数,而您正在那里传递一个函数:http.bananas(function (...) { ... });。如果您使用任何其他值调用该方法,例如http.bananas(4),它将不起作用。这里没有魔法。函数就像任何其他值一样。
  • Line return context(object) 期望 context 参数应该是一个函数,这只是你的代码行为

标签: javascript closures


【解决方案1】:

您正在处理一个回调函数。参数上下文应该是一个函数。 在香蕉函数内部,创建了一个对象,然后将其传递给回调函数上下文。上下文然后执行操作。

请看下文。

//Bananas is a method that takes a callback as a parameter
//A callback is a function that is passed to a function as an argument
function bananas(callback){
    //inside of bananas, we use our callback function
    callback('hello');
}

var log = function (string){
    console.log(string);
}
//We call our bananas function, and pass log as the callback
bananas(log);

/*
Idea of how this is executed
bananas(log);
    -> { 
    ->   log(string);    
    -> }
        string is hello
        log('hello');
        ->  {
        ->     console.log('hello')
        ->  }
*/

//The neat thing about callbacks, you can change the function passed
//So, lets change the log function to do something else
log = function(string){
    //since console.log already logs to the console.
    //lets make this log format the string a bit
    var new_string = "Pretty:\n\t" + string;
    console.log(new_string);
}
//Using console.log as a callback
bananas(console.log);

//using log as a callback
bananas(log);

//Your example uses an anonymous function which can make things seem odd
//Does the same as the first log
bananas(function(string){
    console.log(string);
});

//The reason your test did not work
//I can guess that the error was probably
//sometype is not a function
//functionName(param) only works for functions
var string = 'hello';
string('pie'); //string is not a function

string = function(arg){console.log(arg)};

string('pie') //prints pie

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多