简体   繁体   中英

var $ = this.jQuery cannot understand

(function () {
    var $ = this.jQuery;

    this.myExample = function () {};
}());

Can you tell me what this line means:

var $ = this.jQuery;

I am new to javascript

since it is an IIFE , this refers to the window object inside the scope of the function(since it may not be using strict mode), so we are creating a local variable called $ which refers to the global jQuery variable for easy access.

But it can be simplified as

(function ($) {
    this.myExample = function () {};
}(jQuery));

var $ = this.jQuery; means $ as this.jQuery; in (function () {}()); scope.

It is a variable, you can say that $ will have the value of this.jQuery .

var $ = this.jQuery;

var is a short for variable, $ is the name of that variable, and the value of it is on the right side.

That line is is mapping $ to this.jQuery. Essentially so when calling a function that uses this.jQuery object, $ can be used instead., for example you would use $.somefunction() instead of this.jQuery.somefunction()

The self executing function that encloses those two lines creates the scope. "this" would be the document. If jQuery is loaded then there is this.jQuery so $ becomes this documents jQuery.

In JavaScript, every function is invoked on an object that can be accessed with this . What this is depends on the way the function is called, and defaults to window :

obj1.func(); // "this" inside "func" will be "obj1"
func.call(obj2); // "this" inside "func" will be "obj2"
func(); // "this" will default to "window"

In your case, you are using the third way: (function(){...})() calls the function "unbound", and this will default to the global window object.

var $ = this.jQuery;

Will now bind the value of window.jQuery to the variable name $ , which happens to be a valid identifier name in JavaScript. As the jQuery library provides all its functionality in a global function window.jQuery , this is a convenient way to access it using the shorter name $ :

$("a").click();

To experiment with this in JavaScript, try out the following in your browser's JavaScript console:

function alertThis() { alert(this); }
var obj = {method: alertThis};

alertThis(); // will show something similar to [object Window], as "this" is "window"
alertThis.call("Foobar") // will show "Foobar"
obj.method(); // will show something similar to [object Object], as "this" is "obj"

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