what does require('jquery') return and why multiple assignments

I am new to nodejs and javascript and I tried to get an answer for this question but after investing plenty of time, I couldn't find an answer on the internet.
I now know what require and export are doing. I am analyzing some code and it has the following code line:

var $ = global.jQuery = window.$ = require('jquery');

So here as I have understood the export object of 'jquery' is returned. As I have read from this thread, the code is equal to:

var $ = (global.jQuery = (window.$ = require('jquery')));

I hope that this is correct. If not, what is the code meaning? Then my question is, what is now var $ containing?


what does require('jquery') return

require('jquery') returns a new jquery object, exported by modules.export as you're already familiar with. As any Node module, you can assign this to whatever you like.

Don't be confused by the $ , it's a valid variable name in JavaScript.

why multiple assignments

Syntactical, one-liner convenience, that's all.

  • window.$ is for compatibility with running in the browser
  • global.jQuery is two fold.
  • Having jQuery available is a great fallback for when $ is unavailable such as when running multiple versions of jQuery. I've found this to be fairly common in large projects due to compatibility differences with some 3rd party projects.
  • Since variables are usually locally scoped in Node by default, global has additional, reserved meaning to make the jQuery object available to other portions of code without require() ing it again.
  • $ is the most common usage in the API examples, so it's there for comfort, not necessity.

  • In javascript you can make multiple value assignments in the same statement.

    Multiple = get evaluated right to left. Thus in your example $ is jQuery which is what is imported from the require

    Simple visual example:

    var obj_1={};
    var obj_2={};
    
    // creates properties on both objects and assigns same value to all 3 variables
    var someVar = obj_1.a = obj_2.b = 10; 
    
    console.log('obj_1', obj_1)
    console.log('obj_2', obj_2)
    console.log('someVar', someVar)

    All three of $ , global.jQuery and window.$ are set to the return value of require('jquery') . I'm not entirely sure what the reason is.

    I have used this pattern when working with objects to set a property of an object and a short working variable at the same time, eg:

    this.myMethod = function (value) {
      var n = this.someReallyLongPropertyName = value;
      // no way am I typing this.someReallyLongPropertyName again!
      if (n == 1) return n % n * n + n;
      return 0;
    }
    
    链接地址: http://www.djcxy.com/p/69994.html

    上一篇: 在JavaScript中,创建具有相同值但名称不同的7个变量

    下一篇: 什么需要('jquery')返回以及为什么需要多个分配