javascript函数表现不同 [英] javascript function behaving differently

查看:60
本文介绍了javascript函数表现不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有一个函数

I have a function in javascript:

var a=function greet(){
  console.log("Hello");
}
var b=a;
b();


创建新的var b并将函数 a 分配给 b 日志你好。但是代码:

While creating a new var b and assigning function a to b logs hello.However the code:

function greet(){
  console.log("Hello");
}()

记录错误。为什么?
另外

logs error.Why? Also

(function greet(){
  console.log("Hello");
})()

var a=function greet(){
  console.log("Hello");
}()

日志Hello。请解释这背后的逻辑。

logs "Hello".please explain the logic behind this.

推荐答案

  function greet(){
    console.log("Hello");
  }()

显示错误,因为你立即调用了函数但没有包装函数体'()'。因此,调用函数应立即遵循以下模式:

There showing error because you invoked function immediately but not wrapped function body with '()'. So the invoke function immediately you should follow following pattern:

(fucntion(){ /* code*/ })()

但是你的第一个例子是因为你将函数存储在变量中并稍后将其作为回调样式调用。

But your first example is working because of you storing function in a variable and calling it later as a callback style.

这篇关于javascript函数表现不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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