简体   繁体   中英

JavaScript Dependency Injection + jQuery

I've been looking to refresh my Backbone skills as an upcoming job will be using it (I usually work in Angular or on the back-end). I was looking through todomvc's Backbone example and came across this. I'm wondering why the $ is passed into the closure / anonymous function. If it was dependency injection I would expect underscore to be passed in too. I notced the $ isn't passed in any other files / closures. Github source

/*global Backbone, jQuery, _, ENTER_KEY */
var app = app || {};

(function ($) {
    'use strict';

    // The Application
    // ---------------

    // Our overall **AppView** is the top-level piece of UI.
    app.AppView = Backbone.View.extend({

The purpose of this code is to provide "modularity", privacy and encapsulation for your code.

It is a kind of alias that you are making for jQuery inside the self executing function. The purpose of passing jQuery in to the parenthesis is to provide local scoping to the global variable. This helps reduce the amount of overhead of looking up the $ variable, and allows better compression / optimization for minifiers in some cases.

Sending in $ as an argument to an anonymous function makes $ local to that function which has a small positive performance implication if the $ function is called a lot. This is because javascript searches the local scope for variables first and then traverses down all the way to the window scope (where $ usually lives).

Also it is to avoid a potential conflict of the $ variable. If something else defines a variable named $, your plugin may use the wrong definition

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