Javascript最佳实践,为什么要使用逗号来链接函数/变量声明? [英] Javascript best practices, why to use comma to chain function/variable declarations?

查看:112
本文介绍了Javascript最佳实践,为什么要使用逗号来链接函数/变量声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为jQueryjQueryLog开发一个插件,以允许调试链选择器和返回值。如果您想查看它,可以这里

I've been developing a plugin for jQuery "jQueryLog" to allow for debugging of chain selectors and return values. If you want to check it out, you can do it here

这已是第二个版本。第一个版本实际上是一个编辑过的jQuery,在做这个时我不得不阅读jQuery来了解内部的工作原理。问题来自那里:

This is already a second version. The first version was actually an edited jQuery and while doing it I had to read jQuery to understand how the internals worked. The question comes from there:

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.$,

    // A central reference to the root jQuery(document)
    rootjQuery,

    // A simple way to check for HTML strings or ID strings
    // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
    quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
    (...)

使用声明链+逗号而不仅仅是使用是否有任何重要原因:

Is there any big reason for the using a chain of declarations + "comma" instead of just using:

function jQuery ( selector, context ) { ... }

var _jQuery = window.jQuery;
var _$ = window.$;
etc...

我看到这里的唯一原因是minifier少了无法减少的文字。但是还有其他原因吗?

The only reason I see here is for the minifier to have less literals that can't be cut down. But are there any other reasons?

推荐答案

这是将所有变量保留在函数范围内同时确保它们的简短方法在定义之前不会使用。

It's just a shorter way to keep all the variables in the function scope while making sure they aren't used before they're defined.

JavaScript模式(2010年9月,O'Reilly),Stoyan Stefanov将其称为单个 var 模式

In JavaScript Patterns (Sept. 2010, O'Reilly), Stoyan Stefanov calls it the single var pattern:


JavaScript允许您在
函数中的任何位置拥有多个var语句,它们都像是一样变量在函数的
顶部声明。此行为称为提升。 ...您使用
一个var语句并声明由逗号分隔的多个变量。
在您声明变量时,初始化变量并使用初始
值是一个很好的做法。这可以防止逻辑错误(所有
未初始化和声明的变量都使用值
undefined 进行初始化)并且还提高了代码可读性。

JavaScript enables you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function. This behavior is known as hoisting. ... You use one var statement and declare multiple variables delimited by commas. It's a good practice to also initialize the variable with an initial value at the time you declare it. This can prevent logical errors (all uninitialized and declared variables are initialized with the value undefined) and also improve code readability.

这篇关于Javascript最佳实践,为什么要使用逗号来链接函数/变量声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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