2017-06-13 89 views
0

我刚开始学习javascript等,我从我的朋友那里得到一个项目来看看它,我看到的是他们一直在使用javascript函数作为函数表达式,像这样:关于javascript函数表达式的困惑

var a = function(Id) { 
    //Do something here 
} 

我可以说这样好,they'r那样工作,我要去工作一样,也喜欢机器人,即使我不明白为什么是这样的..

所以我想知道这是什么实际上(在我上面发布的代码中)是那个期望在我们的例子中称为“Id”的1个参数的函数,所以我可以调用它点击一些按钮,例如,或者这个var a是可变的,它被称为“a”,但它可能被称为一个函数,并且实际上它是一个JavaScript函数?

这有点困惑我在这里,我在这个项目中,几乎所有的javascrit功能用于这样看到的,但是这是一个正确的做法还是应该使用命名函数表达式,它可能是这样的:

var a = function myFunction(Id) { 
    //Do something here 
} 

那么现在是什么?我创建了名为myFunction的函数,该函数需要1个名为“Id”的参数,并且可以通过myFunction单击并调用“a”变量来调用它? (如果它是可变的,或者它也函数名或其他)..

谢谢你们 干杯

+0

的https://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname – Andy

回答

1

理解这一点的关键是,在JavaScript中,函数是数据,就像任何其他。所以,如果你都OK理解这一点:

var x = 10; 

如果你要想方设法把x的价值,你会得到10

console.log(x); 

然后,理解这一点并不算多一畦:

var x = function(){ 
    // do something 
} 

如果你试图在这里得到的价值,你会得到函数的实际文本:

console.log(x); // function(){ // do something } 

由于这最后一个版本检索功能,然后你可以通过简单地追加()返回的值,这样调用函数:

x(); // This would invoke the function stored in x 

的另一种方法是用一个“函数声明”看起来像这样:

function x(){ 
    // Do something 
} 

这里,没有变量存储函数...x是函数和调用它,你会直接做到这一点:

x(); 

然而,在JavaScript中,所有的声明是"hoisted"其封闭范围的顶端,所以这一点:

var x = function(){}; 

会导致x声明将被吊起,但x没有价值,而这一点:

function x(){ ...}; 

会导致整个宣言将被悬挂。

不同之处在于声明允许您在代码中调用实际声明之前的函数(因为提升会导致首先读取函数)和表达式,如果您尝试了这种方法,您将得到一个错误说明x is not a function

这里有这样一个例子:

// Print the return value from runing the function who's name is "x". 
 
// This will succeed even though we haven't even declared the function x yet becuase all 
 
// declarations are hoisted to the top of their enclosing scope; 
 
console.log(x()); 
 

 

 
// Print the return value from runing the function stored in the variable called "y": 
 
// This will fail with an error stating that y is not a function because only the variable 
 
// declaration (var y) is hoisted to the top of the enclosing scope, but not the value assigned to it. 
 
console.log(y()); 
 

 

 
// This is a function "declaration" for a function who's name is "x" 
 
function x(){ 
 
    return "hello from function declaration x"; 
 
} 
 

 
// This is a function expression being assigned as the data for a variable 
 
var y = function(){ 
 
    return "hello from function expression y"; 
 
}

两者都是有用的,常常可以互换,但提升会导致您如何(何时)调用函数的差异。

+0

所以'变种X =函数(){// 做某事 }'可以threated可能欺骗函数称为“'x'”,它不带任何参数,只有在我们调用它时才会执行,在某些事件或任何事情上(即“x()'”),而函数x(){.. }; '会在站点/页面被渲染的时候执行,当它被声明的时候会被执行? –

+0

@ Roxy'Pro不完全。 'var x = function(){}'不是一个叫'x'的函数。 'x'是一个存储匿名函数的变量,可以用'x()'调用该函数(在任何适当的时候)。 'function x(){}'是一个命名函数的声明,在适当时也会被调用......这两个函数都不会自动调用。 –