这些声明(在JavaScript中)有什么区别? [英] What's the difference in those declarations (in JavaScript)?

查看:46
本文介绍了这些声明(在JavaScript中)有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Javascript:var functionName = function(){} vs function functionName(){}

在Javascript中,我可以写:

In Javascript I can write:

function TheFunc(arg) {
   ...
}

TheFunc = function(arg) {
   ...
}

TheFunc : function(arg) {
   ...
}

真正的区别是什么,什么时候应该使用?

What's the real difference and when should I use which?

推荐答案

第一种和第二种语法(未在链接的问题中也未提及)之间的一个区别是,如果函数返回函数对象,则使用的结果"TheFunc"将完全不同

One difference between the first and second syntax that's not mentioned (not in the linked questions as well) is that if the function returns a function object the results of using 'TheFunc' will be quite different

TheFunc = function(arg) {
  return function(x) {
    return arg+x;
  }
}(5);
res = TheFunc(2); // res == 7

使其等同于

TheFunc = function(5) {
  return function(x) {
    return 5+x;
  }
}
res = TheFunc(2); // res == 7

因为该函数是匿名的.虽然

because the function was anonymous. While

function TheFunc(arg) {
  return function(x) {
    return arg+x;
  }
}

byFive = TheFunc(5);
res = byFive(2); // res == 7

将具有相同的结果,但是会使该函数在工厂中可重用.

would have the same result, but making the function factory reusable.

在这些示例中,实际用途尚不清楚,但是,例如在基于回调的调用围绕着复杂的钩子系统(例如带有插件的系统)存在的情况下,它是必不可少的.

The practical uses won't be that clear in these examples, however it can be indispensable, for example, in situations where a complex hook system exists built around callback based calls - such as systems with plug-ins:

// state object
function state(args) {
  this.parse = function(data){
    data = this.pre_parser(data);

    // go on transforming data

    return data;
  }
}
state.prototype.pre_parser_factory = function(options){
  ...
}

var st = new state(args);
async_call( function(data, options){
              st.pre_parser = st.pre_parser_factory(options);
              res = st.parse(data);
            })

这篇关于这些声明(在JavaScript中)有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆