Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/424.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript var functionName=function(){}vs function functionName(){}_Javascript_Function_Syntax_Idioms - Fatal编程技术网

Javascript var functionName=function(){}vs function functionName(){}

Javascript var functionName=function(){}vs function functionName(){},javascript,function,syntax,idioms,Javascript,Function,Syntax,Idioms,我最近开始维护其他人的JavaScript代码。我正在修复bug,添加特性,并试图整理代码,使其更加一致 以前的开发人员使用了两种声明函数的方法,我无法确定这背后是否有原因 这两种方式是: var functionOne = function() { // Some code }; 使用这两种不同方法的原因是什么?每种方法的优缺点是什么?有什么可以用一个方法完成而不能用另一个方法完成的吗?区别在于functionOne是一个函数表达式,因此只有在到达该行时才定义,而functionTw

我最近开始维护其他人的JavaScript代码。我正在修复bug,添加特性,并试图整理代码,使其更加一致

以前的开发人员使用了两种声明函数的方法,我无法确定这背后是否有原因

这两种方式是:

var functionOne = function() {
    // Some code
};

使用这两种不同方法的原因是什么?每种方法的优缺点是什么?有什么可以用一个方法完成而不能用另一个方法完成的吗?

区别在于
functionOne
是一个函数表达式,因此只有在到达该行时才定义,而
functionTwo
是一个函数声明,并且在执行其周围的函数或脚本时立即定义(到期日)

例如,函数表达式:

var xyz = function(){};
var abc = function() {};
var fn=function(){
  console.log("Hello");
}
fn();
//类型错误:functionOne不是函数
函数一();
var functionOne=函数(){
log(“你好!”);

}不同之处在于,
functionOne
是一个函数表达式,因此仅在到达该行时定义,而
functionTwo
是一个函数声明,在执行其周围的函数或脚本时定义(由于)

例如,函数表达式:

var xyz = function(){};
var abc = function() {};
var fn=function(){
  console.log("Hello");
}
fn();
//类型错误:functionOne不是函数
函数一();
var functionOne=函数(){
log(“你好!”);

}
首先我想更正Greg:
函数abc(){}
也有作用域-名称
abc
在遇到此定义的作用域中定义。示例:

function xyz(){
  function abc(){};
  // abc is defined here...
}
// ...but not here
其次,可以将两种风格结合起来:

var xyz = function abc(){};
xyz
将像往常一样定义,
abc
在除InternetExplorer之外的所有浏览器中都未定义-不要依赖于它的定义。但它将在其主体内部定义:

var xyz = function abc(){
  // xyz is visible here
  // abc is visible here
}
// xyz is visible here
// abc is undefined here
如果要在所有浏览器上别名函数,请使用以下声明:

function abc(){};
var xyz = abc;
function abc(){}
function abc(){}
function fn(){
  console.log("Hello");
}
fn();
在这种情况下,
xyz
abc
都是同一对象的别名:

console.log(xyz === abc); // prints "true"
使用组合样式的一个引人注目的原因是函数对象的“name”属性(不受InternetExplorer的支持)

function abc(){};
console.log(abc.name); // prints "abc"
var abc = function(){};
abc = function(){};
它的名称是自动分配的。但是当你定义它时

var abc = function(){};
console.log(abc.name); // prints ""
它的名称为空-我们创建了一个匿名函数并将其分配给某个变量

使用组合样式的另一个很好的原因是使用短的内部名称来引用自身,同时为外部用户提供一个长的不冲突的名称:

// Assume really.long.external.scoped is {}
really.long.external.scoped.name = function shortcut(n){
  // Let it call itself recursively:
  shortcut(n - 1);
  // ...
  // Let it pass itself as a callback:
  someFunction(shortcut);
  // ...
}
在上面的示例中,我们可以对外部名称执行相同的操作,但这样做太麻烦(而且速度较慢)

(引用自身的另一种方法是使用
参数.callee
,它仍然相对较长,在严格模式下不受支持。)

实际上,JavaScript对这两个语句的处理方式不同。这是一个函数声明:

function abc(){};
var xyz = abc;
function abc(){}
function abc(){}
function fn(){
  console.log("Hello");
}
fn();
abc
在当前范围内的任何地方都有定义:

// We can call it here
abc(); // Works

// Yet, it is defined down there.
function abc(){}

// We can call it again
abc(); // Works
此外,它通过
返回
语句提升:

// We can call it here
abc(); // Works
return;
function abc(){}
这是一个函数表达式:

var xyz = function(){};
var abc = function() {};
var fn=function(){
  console.log("Hello");
}
fn();
xyz
此处从分配点定义:

// We can't call it here
xyz(); // UNDEFINED!!!

// Now it is defined
xyz = function(){}

// We can call it here
xyz(); // works
函数声明与函数表达式是格雷格所证明的差异的真正原因

有趣的事实:

var xyz = function abc(){};
console.log(xyz.name); // Prints "abc"
就个人而言,我更喜欢“函数表达式”声明,因为这样我可以控制可见性

function abc(){};
console.log(abc.name); // prints "abc"
var abc = function(){};
abc = function(){};
我知道我在本地定义了这个函数

function abc(){};
console.log(abc.name); // prints "abc"
var abc = function(){};
abc = function(){};
我知道我在全局范围内定义了它,但前提是我没有在作用域链中的任何位置定义
abc
。这种定义风格即使在
eval()
中使用,也具有弹性

function abc(){};

取决于上下文,可能会让您猜测它的实际定义位置,特别是在
eval()
的情况下-答案是:它取决于浏览器。

首先我想更正Greg:
函数abc(){}
也有作用域-名称
abc
在遇到此定义的作用域中定义。示例:

function xyz(){
  function abc(){};
  // abc is defined here...
}
// ...but not here
其次,可以将两种风格结合起来:

var xyz = function abc(){};
xyz
将像往常一样定义,
abc
在除InternetExplorer之外的所有浏览器中都未定义-不要依赖于它的定义。但它将在其主体内部定义:

var xyz = function abc(){
  // xyz is visible here
  // abc is visible here
}
// xyz is visible here
// abc is undefined here
如果要在所有浏览器上别名函数,请使用以下声明:

function abc(){};
var xyz = abc;
function abc(){}
function abc(){}
function fn(){
  console.log("Hello");
}
fn();
在这种情况下,
xyz
abc
都是同一对象的别名:

console.log(xyz === abc); // prints "true"
使用组合样式的一个引人注目的原因是函数对象的“name”属性(不受InternetExplorer的支持)

function abc(){};
console.log(abc.name); // prints "abc"
var abc = function(){};
abc = function(){};
它的名称是自动分配的。但是当你定义它时

var abc = function(){};
console.log(abc.name); // prints ""
它的名称为空-我们创建了一个匿名函数并将其分配给某个变量

使用组合样式的另一个很好的原因是使用短的内部名称来引用自身,同时为外部用户提供一个长的不冲突的名称:

// Assume really.long.external.scoped is {}
really.long.external.scoped.name = function shortcut(n){
  // Let it call itself recursively:
  shortcut(n - 1);
  // ...
  // Let it pass itself as a callback:
  someFunction(shortcut);
  // ...
}
在上面的示例中,我们可以对外部名称执行相同的操作,但这样做太麻烦(而且速度较慢)

(引用自身的另一种方法是使用
参数.callee
,它仍然相对较长,在严格模式下不受支持。)

实际上,JavaScript对这两个语句的处理方式不同。这是一个函数声明:

function abc(){};
var xyz = abc;
function abc(){}
function abc(){}
function fn(){
  console.log("Hello");
}
fn();
abc
在当前范围内的任何地方都有定义:

// We can call it here
abc(); // Works

// Yet, it is defined down there.
function abc(){}

// We can call it again
abc(); // Works
此外,它通过
返回
语句提升:

// We can call it here
abc(); // Works
return;
function abc(){}
这是一个函数表达式:

var xyz = function(){};
var abc = function() {};
var fn=function(){
  console.log("Hello");
}
fn();
xyz
此处从分配点定义:

// We can't call it here
xyz(); // UNDEFINED!!!

// Now it is defined
xyz = function(){}

// We can call it here
xyz(); // works
函数声明与函数表达式是格雷格所证明的差异的真正原因

有趣的事实:

var xyz = function abc(){};
console.log(xyz.name); // Prints "abc"
就我个人而言,我更喜欢“函数表达式”声明,因为这样我可以控制可见性
func.name: 
Trace:
a@http://localhost:8000/test.js:4:5
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: b
Trace:
b@http://localhost:8000/test.js:7:9
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: d
Trace:
d@http://localhost:8000/test.js:10:9
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: 
Trace:
a@http://localhost:8000/test.js:4:5
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: b
Trace:
b@http://localhost:8000/test.js:7:9
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: d
Trace:
d@http://localhost:8000/test.js:10:9
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: 
Trace:
e.i@http://localhost:8000/test.js:17:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: j
Trace:
j@http://localhost:8000/test.js:20:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: l
Trace:
l@http://localhost:8000/test.js:23:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: 
Trace:
m</<@http://localhost:8000/test.js:28:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: n
Trace:
n@http://localhost:8000/test.js:33:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1


func.name: p
Trace:
p@http://localhost:8000/test.js:38:13
@http://localhost:8000/test.js:47:9
@http://localhost:8000/test.js:54:1
func.name: undefined
Trace:
Error
   at a (http://localhost:8000/test.js:4:5)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at b (http://localhost:8000/test.js:7:9)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at d (http://localhost:8000/test.js:10:9)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at a (http://localhost:8000/test.js:4:5)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at b (http://localhost:8000/test.js:7:9)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at d (http://localhost:8000/test.js:10:9)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at e.i (http://localhost:8000/test.js:17:13)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at j (http://localhost:8000/test.js:20:13)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at l (http://localhost:8000/test.js:23:13)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at Anonymous function (http://localhost:8000/test.js:28:13)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at n (http://localhost:8000/test.js:33:13)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)


func.name: undefined
Trace:
Error
   at p (http://localhost:8000/test.js:38:13)
   at Anonymous function (http://localhost:8000/test.js:47:9)
   at Global code (http://localhost:8000/test.js:42:1)
func.name: 
Trace:
a@http://localhost:8000/test.js:4:22
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: b
Trace:
b@http://localhost:8000/test.js:7:26
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: d
Trace:
d@http://localhost:8000/test.js:10:26
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: 
Trace:
a@http://localhost:8000/test.js:4:22
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: b
Trace:
b@http://localhost:8000/test.js:7:26
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: d
Trace:
d@http://localhost:8000/test.js:10:26
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: 
Trace:
i@http://localhost:8000/test.js:17:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: j
Trace:
j@http://localhost:8000/test.js:20:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: l
Trace:
l@http://localhost:8000/test.js:23:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: 
Trace:
http://localhost:8000/test.js:28:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: n
Trace:
n@http://localhost:8000/test.js:33:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33

func.name: p
Trace:
p@http://localhost:8000/test.js:38:30
http://localhost:8000/test.js:47:13
reduce@[native code]
global code@http://localhost:8000/test.js:44:33
var foo = function foo() {};
function foo() {};
function foo() {};
var foo = function foo() {};
var foo = undefined;
foo = function foo() {};
function outerFunction() {
    function foo() {
       return 1;
    }
    return foo();
    function foo() {
       return 2;
    }
}
alert(outerFunction()); // Displays 2
function foo() {  // The first function declaration is moved to top
    return 1;
}
function foo() {  // The second function declaration is moved to top
    return 2;
}
function outerFunction() {
    return foo();
}
alert(outerFunction()); //So executing from top to bottom,
                        //the last foo() returns 2 which gets displayed
function outerFunction() {
    var foo = function() {
       return 1;
    }
    return foo();
    var foo = function() {
       return 2;
    }
}
alert(outerFunction()); // Displays 1
function outerFunction() {
   var foo = undefined;
   var foo = undefined;

   foo = function() {
      return 1;
   };
   return foo ();
   foo = function() {   // This function expression is not reachable
      return 2;
   };
}
alert(outerFunction()); // Displays 1
if (test) {
    function x() { doSomething(); }
}
var today = function today() {return new Date()}
functionOne();
var functionOne = function() {
    // Some code
};
functionOne();
function functionOne() {
   // Some code
}
global_Page = 10;                                               var global_Page;      « undefined
    « Integer literal, Number Type.   -------------------       global_Page = 10;     « Number         
global_Page = 'Yash';                 |   Interpreted   |       global_Page = 'Yash'; « String
    « String literal, String Type.    «       AS        «       global_Page = true;   « Boolean 
var global_Page = true;               |                 |       global_Page = function (){          « function
    « Boolean Type                    -------------------                 var local_functionblock;  « undefined
global_Page = function (){                                                local_functionblock = 777;« Number
    var local_functionblock = 777;                              };  
    // Assigning function as a data.
};  
function Identifier_opt ( FormalParameterList_opt ) { 
      FunctionBody | sequence of statements

      « return;  Default undefined
      « return 'some data';
}
Scope with respect to function-block global. 
Scope with respect to page undefined | not available.
function globalAccess() {                                  function globalAccess() {      
}                                  -------------------     }
globalAccess();                    |                 |     function globalAccess() { « Re-Defined / overridden.
localAccess();                     «   Hoisted  As   «         function localAccess() {
function globalAccess() {          |                 |         }
     localAccess();                -------------------         localAccess(); « function accessed with in globalAccess() only.
     function localAccess() {                              }
     }                                                     globalAccess();
}                                                          localAccess(); « ReferenceError as the function is not defined
        10;                 « literal
       (10);                « Expression                (10).toString() -> '10'
var a;                      
    a = 10;                 « Expression var              a.toString()  -> '10'
(function invoke() {        « Expression Function
 console.log('Self Invoking');                      (function () {
});                                                               }) () -> 'Self Invoking'

var f; 
    f = function (){        « Expression var Function
    console.log('var Function');                                   f ()  -> 'var Function'
    };
(function selfExecuting(){
    console.log('IIFE - Immediately-Invoked Function Expression');
}());

var anonymous = function (){
    console.log('anonymous function Expression');
};

var namedExpression = function for_InternalUSE(fact){
    if(fact === 1){
        return 1;
    }

    var localExpression = function(){
        console.log('Local to the parent Function Scope');
    };
    globalExpression = function(){ 
        console.log('creates a new global variable, then assigned this function.');
    };

    //return; //undefined.
    return fact * for_InternalUSE( fact - 1);   
};

namedExpression();
globalExpression();
var anonymous;
var namedExpression;
var globalExpression;

anonymous = function (){
    console.log('anonymous function Expression');
};

namedExpression = function for_InternalUSE(fact){
    var localExpression;

    if(fact === 1){
        return 1;
    }
    localExpression = function(){
        console.log('Local to the parent Function Scope');
    };
    globalExpression = function(){ 
        console.log('creates a new global variable, then assigned this function.');
    };

    return fact * for_InternalUSE( fact - 1);    // DEFAULT UNDEFINED.
};

namedExpression(10);
globalExpression();
function Shape(id) { // Function Declaration
    this.id = id;
};
    // Adding a prototyped method to a function.
    Shape.prototype.getID = function () {
        return this.id;
    };
    Shape.prototype.setID = function ( id ) {
        this.id = id;
    };

var expFn = Shape; // Function Expression

var funObj = new Shape( ); // Function Object
funObj.hasOwnProperty('prototype'); // false
funObj.setID( 10 );
console.log( funObj.getID() ); // 10
const fn = (item) => { return item & 1 ? 'Odd' : 'Even'; };
console.log( fn(2) ); // Even
console.log( fn(3) ); // Odd
var func = new Function("x", "y", "return x*y;");
function secondFunction(){
   var result;
   result = func(10,20);
   console.log ( result );
}

secondFunction()
function fn(){
  console.log("Hello");
}
fn();
var fn=function(){
  console.log("Hello");
}
fn();
var functionOne = function() {
    // Some code
};
function functionTwo() {
    // Some code
}