简体   繁体   English

这是什么JavaScript编码风格?

[英]What javascript coding style is this?

I am working on maintaining a ASP.NET MVC application that has the following coding style. 我正在努力维护具有以下编码风格的ASP.NET MVC应用程序。 The view has: 该观点有:

<script type="text/javascript">

    $(document).ready(function() {

        SAVECUSTOMERS.init();
    });
</script>

There is a js file included that goes along these lines: 这里包含一个js文件:

var SAVECUSTOMERS = (function() {

    init = function () {

        $("#saveCust").bind("click", OnSave);
        $("#cancel").bind("click", OnCancel);

    },

    OnSave= function() {

        //Save Logic;

    },

    OnCancel = function() {
                //Cancel logic;

    }

    return { init: init };

})();
  1. Is this a best practices JS coding style? 这是JS编码风格的最佳实践吗? Is the intent to have non obtrusive JS? 意图是非突兀的JS吗?
  2. What is the SAVECUSTOMERS? 什么是SAVECUSTOMERS? I understand that there are different ways of creating classes in javascript (per this link ), but this style does not fall into any of those categories listed 我知道有不同的方法在javascript中创建类(根据此链接 ),但此样式不属于列出的任何类别
  3. Where can I find more information on this style of JS coding? 我在哪里可以找到有关这种JS编码风格的更多信息?

1) Using a $(document).ready (or similar function from another library) function is considered standard practice in JavaScript. 1)使用$(document).ready(或来自另一个库的类似函数)函数认为是JavaScript中的标准实践。 First of all, it ensures your JavaScript executes on page that has finished evaluating/building it's DOM. 首先,它确保您的JavaScript在已完成评估/构建DOM的页面上执行。 And it also abstracts away some of the browser-implementation inconsistencies when identifying when the DOM is in fact ready. 并且它还在识别DOM实际上准备就绪时抽象出一些浏览器实现的不一致性。 But I assume you are mainly referring to the 2nd code block. 但我假设你主要是指第二个代码块。

What you see there is that SAVECUSTOMERS is assigned the result of a self-executing an anonymous function. 你看到的是,SAVECUSTOMERS被分配了一个自动执行匿名函数的结果。 This is done for a few reasons, the most common being the ability to control the scope and 'namespace' of the functions and data inside the anonymous function. 这样做有几个原因,最常见的是能够控制匿名函数内的函数和数据的范围和“命名空间”。 This is because JavaScript has lexical scope, and not block level scope. 这是因为JavaScript具有词法范围,而不是块级范围。

The practice of using these self-invoking functions in JavaScript is very common 在JavaScript中使用这些自调用函数的做法非常普遍

However the code itself has several problems. 但是代码本身有几个问题。 The variables init, OnSave and OnCancel are declared as global variables (because the var keyword was omitted). 变量init,OnSave和OnCancel被声明为全局变量(因为省略了var关键字)。 This largely defeats the purpose of wrapping them in an self-invoking function. 这在很大程度上违背了将它们包装在自我调用函数中的目的。 Furthermore, the contents of that function are using a mix of object assignment syntax and standard expression syntax, which will result in syntax errors. 此外,该函数的内容使用对象分配语法和标准表达式语法的混合,这将导致语法错误。

Also, by returning only the init function, the onSave and onCancel functions have been effectively 'hidden' or made 'private' through the use of closures. 此外,通过仅返回init函数,onSave和onCancel函数已通过使用闭包被有效地“隐藏”或变为“私有”。 This helps keep namespaces clean and encapsulated. 这有助于保持名称空间的清洁和封装。

If I were writing this code (some personal perferences here, there are a few ways to accomplish something simliar), then it would look like this: 如果我正在编写这段代码(这里有一些个人的贡献,有几种方法可以实现simliar),那么它看起来像这样:

var SaveCustomers = (function($) {
    var init = function () {
        $("#saveCust").bind("click", onSave);
        $("#cancel").bind("click", onCancel);
    };

    var onSave = function() {
        //Save Logic;
    };

    var onCancel = function() {
        //Cancel logic;
    }

    return { init: init };

})(jQuery);

Some notes on the above: 关于上述的一些注意事项:

  • I declare variables using the var keyword. 我使用var关键字声明变量。 This keeps their scope local to this function (you could also technically use named functions declarations as well) 这使它们的范围保持在本函数的本地(你也可以在技术上使用命名函数声明)

  • I pass jQuery as the parameter in the self-invoking function, and assign it to $ as the argument in the function call. 我将jQuery作为自调用函数中的参数传递,并将其作为函数调用中的参数赋值给$。 This protects the $ variable inside the function so that we know it references jQuery, and hasn't been munged by a secondary library that also uses $. 这保护了函数内部的$变量,以便我们知道它引用了jQuery,并且还没有被也使用$的二级库所驱动。

2) SAVECUSTOMERS is a basic JavaScript object, which has a single owned property called 'init', whose value is a function, as defined by the init declaration inside the execution. 2)SAVECUSTOMERS是一个基本的JavaScript对象,它有一个名为'init'的属性,其值是一个函数,由执行中的init声明定义。

3) Not sure about how to answer this question - your best bet for understanding JavaScript best practices is to read through other JavaScript code that is known to be of quality, such as the jQuery source, or Prototype, or Underscore, etc. 3)不确定如何回答这个问题 - 理解JavaScript最佳实践的最佳选择是阅读已知具有高质量的其他JavaScript代码,例如jQuery源代码,Prototype或Underscore等。

这种风格被称为jquery ...你检查过JQuery网站,看看它...

This is called self-invoking functions in javascript. 这在javascript中称为自调用函数 One of the articles I am giving below. 我在下面给出的一篇文章。 you can get more on google. 你可以在谷歌上获得更多。

http://2007-2010.lovemikeg.com/2008/08/17/a-week-in-javascript-patterns-self-invocation/ http://2007-2010.lovemikeg.com/2008/08/17/a-week-in-javascript-patterns-self-invocation/

If you are referring to the $ programming, then its related to JQuery which other answers have provided links too. 如果你指的是$编程,那么它与JQuery有关,其他答案也提供了链接。

It's using the JQuery library . 它正在使用JQuery库

JQuery includes a function called $() , which allows you to select elements from the DOM using a CSS-like syntax. JQuery包含一个名为$()的函数,它允许您使用类似CSS的语法从DOM中选择元素。

The $(document).ready bit is a standard JQuery method for making sure that the enclosed code only gets run after the page has finished loading. $(document).ready位是一个标准的JQuery方法,用于确保封装的代码仅在页面加载完成后运行。 This is required to ensure that events get correctly attached to the relevant DOM objects. 这是确保事件正确附加到相关DOM对象所必需的。

The bit with functions being used as arguments for others functions is known as a 'closure' it's a very common way of writing Javascript, but in particular when using JQuery, which goes out of its way to make things easy to do and minimal code with this coding style. 将函数用作其他函数的参数的位称为“闭包”,它是编写Javascript的一种非常常见的方式,但特别是在使用JQuery时,它使用简单易用的方法和最少的代码。这种编码风格。

See this page: http://blog.morrisjohns.com/javascript_closures_for_dummies for a beginners discussion of how closures work in Javascript and how to write them (note that this page doesn't look at JQuery at all; closures are a Javascript feature that is used heavily by JQuery, but you don't need JQuery to write closures) 请参阅此页面: http//blog.morrisjohns.com/javascript_closures_for_dummies,以便初学者讨论闭包在Javascript中的工作方式以及如何编写它们(请注意,此页面根本不看JQuery;闭包是一个Javascript功能,被JQuery大量使用,但你不需要JQuery来编写闭包)

This is a normal way to use jQuery for handling events. 这是使用jQuery处理事件的常用方法。

What basicly happens is that you check that the document is loaded hence 基本上发生的是您检查文档是否已加载

 $(document).ready(function() {

        SAVECUSTOMERS.init();
    });

And when it is you start to add your bindings to buttons or what ever they might be. 当你开始将你的绑定添加到按钮或它们可能是什么时。

The intent of the code in SAVECUSOMTERS is to mimic private and public properties in objects. SAVECUSOMTERS中代码的目的是模仿对象中的私有属性和公共属性。 Since JS does not support these by default, this self invoking function executes and returns a certain number of properties. 由于JS默认不支持这些,因此这个自调用函数执行并返回一定数量的属性。 In this case it returns the 'init' method. 在这种情况下,它返回'init'方法。 Despite the fact that you see OnSave and OnClick, you'll find that you can't access them at all. 尽管您看到OnSave和OnClick,但您会发现根本无法访问它们。 They are "private" and only used internally within that function. 它们是“私有的”,仅在该函数内部使用。

The $() function is part of a javascript library called jQuery http://jquery.com It's a pretty well rounded library and primarily is used for DOM manipulation. $()函数是一个名为jQuery http://jquery.com的javascript库的一部分。它是一个非常全面的库,主要用于DOM操作。

The $(document).ready() function is a way for jQuery to continuously poll the page until it is loaded. $(document).ready()函数是jQuery连续轮询页面直到加载的一种方式。 When it is, the javascript within is executed. 如果是,则执行内部的javascript。

  1. The goal is to have public and private functions. 目标是拥有公共和私人职能。 OnSave and OnCancel are private functions that are only accessible within the scope of the self-executing anonymous (function() { ... } ()) which returns an object that gives access to the init function publicly. OnSaveOnCancel是私有函数,只能在自执行匿名(function() { ... } ())范围内访问,它返回一个公共访问init函数的对象。

  2. SAVECUSTOMERS becomes the object returned by the above mentioned function, ie { init: init } , an object with one method init that has access to the functions within that closure. SAVECUSTOMERS成为上述函数返回的对象,即{ init: init } ,一个具有一个方法init的对象,可以访问该闭包内的函数。

  3. You can read Douglas Crockford's Javascript: The Good Parts or Stoyan Stefanov's Javascript Patterns 你可以阅读Douglas Crockford的Javascript:The Good Parts或Stoyan Stefanov的Javascript模式

Other notes: 其他说明:

  • The $() functions belong to the jQuery library $()函数属于jQuery库
  • There are syntax errors because the functions should be separated by ; 存在语法错误,因为函数应该由; not , since they are within a function, not an object. ,因为它们在一个函数内,而不是一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM