Javascript最佳实践

Javascript最佳实践

本文介绍了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.

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

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

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

08-22 12:12