我最近开始保持别人的JavaScript代码,我正在修复错误,添加功能,也试图更新代码并使其更加一致。

以前的开发人员使用了两种方式来宣布功能,我无法解决是否有原因。

兩種方式是:

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

使用这两种不同的方法的原因是什么?每个方法的优点和缺点是什么?可以用一种方法做些什么,不能用另一种方法做些什么?


当前回答

其他评论家已经覆盖了上述两种变量的种子差异,我想注意一个风格差异:只有“分配”变量才能设置另一个对象的属性。

我经常用这样的模式创建JavaScript模块:

(function(){
    var exports = {};

    function privateUtil() {
            ...
    }

    exports.publicUtil = function() {
            ...
    };

    return exports;
})();

使用此模式,您的公共功能将使用任务,而您的私人功能则使用声明。

(请注意,任务应在声明后需要半分,而声明则禁止。

其他回答

function xyz(){
  function abc(){};
  // abc is defined here...
}
// ...but not here

其次,可以结合两种风格:

var xyz = function abc(){};

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;

console.log(xyz === abc); // prints "true"

function abc(){};
console.log(abc.name); // prints "abc"

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);
  // ...
}

在上面的例子中,我们可以用外部名称做同样的事情,但它会太不多(而且更慢)。

function abc(){}

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(){};

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"

var abc = function(){};

我知道我定义了函数本地,当我定义了函数如

abc = function(){};

function abc(){};

它取决于背景,可能会让你猜测它实际上在哪里定义,特别是在 eval()的情况下 - 答案是: 它取决于浏览器。

第一個例子是一個功能宣言:

function abc(){}

第二个例子是函数表达:

var abc = function() {};

在第一個例子中,整個函數宣言都被封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封封。

把它简单地说:

//this will work
abc(param);
function abc(){}

//this would fail
abc(param);
var abc = function() {}

要了解更多关于这个主题,我强烈推荐这个链接。

区别在于,函数One 是一种函数表达式,因此只有在到达该行时才定义,而函数Two 是一种函数声明,并在其周围函数或脚本执行后才定义。

例如,函数表达式:

// TypeError: functionOne 不是函数函数One(); var 函数One = 函数() { console.log(“Hello!”); };

还有一个功能声明:

// 输出: “Hello!”函数Two();函数函数Two() { console.log(“Hello!”); }

“使用严格”; { // 注意此区块! 函数三() { console.log(“Hello!”); } } 函数三(); // 参考错误

function x() {
    console.log('x');
}

x(); // Works even though it's above the declaration
function x() {
    console.log('x');
}

if (someCondition) {
    function foo() {    // <===== HERE THERE
    }                   // <===== BE DRAGONS
}

"use strict";
if (someCondition) {
    foo();               // Works just fine
    function foo() {
    }
}
console.log(typeof foo); // "undefined" (`foo` is not in scope here
                         // because it's not in the same block)

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

名称函数表达式

var z = function w() {
    console.log('zw')
};

var z = function w() {
    console.log(typeof w); // "function"
};
console.log(typeof w);     // "undefined"

配件功能启动器(ES5+)

var obj = {
    value: 0,
    get f() {
        return this.value;
    },
    set f(v) {
        this.value = v;
    }
};
console.log(obj.f);         // 0
console.log(typeof obj.f);  // "number"

您还可以使用 Object.defineProperty、Object.defineProperties 和 Object.create 更不熟悉的第二个论点创建附件功能。

Arrow 功能表达式(ES2015+)

var a = [1, 2, 3];
var b = a.map(n => n * 2);
console.log(b.join(", ")); // 2, 4, 6

看到 n => n * 2 隐藏在地图() 呼叫? 这是一个函数。

关于箭头功能的一些事情:

他們沒有自己的這一點. 相反,他們關閉了他們所定義的背景的這一點. (他們也關閉了論點,在相關的情況下,超級.) 這意味著他們內在的這一點是相同的這一點,在那裡他們是創造的,並且不能改變。

var a = [1, 2, 3];
var b = a.map((n, i) => n * i);
console.log(b.join(", ")); // 0, 2, 6

如果您正在做一个单一表达式以上,请使用 {} 和一个明确的回报(如果您需要返回值),如正常:

var a = [
  {first: "Joe", last: "Bloggs"},
  {first: "Albert", last: "Bloggs"},
  {first: "Mary", last: "Albright"}
];
a = a.sort((a, b) => {
  var rv = a.last.localeCompare(b.last);
  if (rv === 0) {
    rv = a.first.localeCompare(b.first);
  }
  return rv;
});
console.log(JSON.stringify(a));

对象初步化方法宣言(ES2015+)

var o = {
    foo() {
    }
};

var o = {
    foo: function foo() {
    }
};

ES2015为我们提供类合成,包括声明的建筑师和方法:

class Person {
    constructor(firstName, lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    getFullName() {
        return this.firstName + " " + this.lastName;
    }
}

你在那里发布的两个代码剪辑,几乎所有目的都会以相同的方式行事。

然而,行为的差异是,在第一个变量(有函数One = 函数() {}),该函数只能在代码中的那个点之后被称为。

第二个选项(函数Two()),函数可用于代码,运行在函数被宣布的地方。

这是因为第一种变量,函数在运行时分配给变量foo;第二种函数在运行时分配给这个识别器,foo。

更多技术信息

JavaScript 有三种方式来定义功能。

你的第一个剪辑显示一个函数表达式. 这意味着使用“函数”操作员创建一个函数 - 该操作员的结果可以存储在任何变量或对象属性. 函数表达式是强大的这种方式. 函数表达式经常被称为“匿名函数”,因为它不需要一个名字, 你的第二个例子是一个函数声明。