简体   繁体   中英

What javascript coding style is this?

I am working on maintaining a ASP.NET MVC application that has the following coding style. The view has:

<script type="text/javascript">

    $(document).ready(function() {

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

There is a js file included that goes along these lines:

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? Is the intent to have non obtrusive JS?
  2. What is the 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
  3. Where can I find more information on this style of JS coding?

1) Using a $(document).ready (or similar function from another library) function is considered standard practice in JavaScript. First of all, it ensures your JavaScript executes on page that has finished evaluating/building it's DOM. And it also abstracts away some of the browser-implementation inconsistencies when identifying when the DOM is in fact ready. 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. 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.

The practice of using these self-invoking functions in JavaScript is very common

However the code itself has several problems. The variables init, OnSave and OnCancel are declared as global variables (because the var keyword was omitted). 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. 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:

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

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.

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.

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

This is called self-invoking functions in 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/

If you are referring to the $ programming, then its related to JQuery which other answers have provided links too.

It's using the JQuery library .

JQuery includes a function called $() , which allows you to select elements from the DOM using a CSS-like syntax.

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. This is required to ensure that events get correctly attached to the relevant DOM objects.

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.

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)

This is a normal way to use jQuery for handling events.

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. Since JS does not support these by default, this self invoking function executes and returns a certain number of properties. In this case it returns the 'init' method. Despite the fact that you see OnSave and OnClick, you'll find that you can't access them at all. 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.

The $(document).ready() function is a way for jQuery to continuously poll the page until it is loaded. When it is, the javascript within is executed.

  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.

  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.

  3. You can read Douglas Crockford's Javascript: The Good Parts or Stoyan Stefanov's Javascript Patterns

Other notes:

  • The $() functions belong to the jQuery library
  • There are syntax errors because the functions should be separated by ; not , since they are within a function, not an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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