为什么jQuery源代码使用逗号运算符进行变量赋值呢?

Pau*_*ite 3 javascript jquery

这是从jQuery源代码(1.7.1)开始的摘录:

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    },

    // Map over jQuery in case of overwrite
    _jQuery = window.jQuery,

    // Map over the $ in case of overwrite
    _$ = window.$,


    // ...continues...


    // [[Class]] -> type pairs
    class2type = {};
Run Code Online (Sandbox Code Playgroud)

代码是一系列变量赋值,全部由逗号运算符连接.据我了解逗号运算符,它会在它之前和之后计算表达式,并返回后者的值.

由于变量赋值链没有被分配给任何东西,因此让我感到震惊的是代码可以用分号代替逗号来重写,而不会改变它的运算方式.例如

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
        // The jQuery object is actually just the init constructor 'enhanced'
        return new jQuery.fn.init( selector, context, rootjQuery );
    }; /* <----- semicolon */

    // Map over jQuery in case of overwrite
    _jQuery = window.jQuery; /* <----- semicolon */

    // Map over the $ in case of overwrite
    _$ = window.$; /* <----- semicolon */

    // ...and so on.
Run Code Online (Sandbox Code Playgroud)
  1. 如果用这样的分号重写,代码是否会产生相同的效果,或者我错过了什么?

  2. 如果有同样的效果,是什么风格的原因,用逗号写呢?(我知道,例如,Crockford不喜欢逗号运算符(见底部附近),虽然我不知道为什么.)

kir*_*oid 8

No.逗号分隔var声明,全部使用第一个var前缀.例如:

var a = 1, // local
    b = 2; // local


var a = 1; // local
    b = 2; // global!
Run Code Online (Sandbox Code Playgroud)

为了达到同样的效果,请这样写:

var a = 1; // local
var b = 2; // local
Run Code Online (Sandbox Code Playgroud)