简体   繁体   中英

Set global variable inside `$(document).ready(function()`

I try to set a global variable inside $(document).ready(function()

$(document).ready(function(){
    $(".editCommentLink").on("click", function (e) {
        e.preventDefault();
        var window.comment_id = $(e.target).attr("id");

It throws error:

var window.comment_id = $(e.target).attr("id");
Uncaught SyntaxError: Unexpected token .

When try to place var comment_id elsewhere, it constantly report undefined

Var is not required. Just use window.global_variable = “your_value”

For more information about variable scope in javascript please read following article of MDN lexical scope

window.myVar or window["myVar"] is an explicit way to refer to a global variable.

A variable is a global variable if it's declared outside of a function (with or without "var"), or if it's declared inside a function without using "var", or if it's declared as window.myVar or window["myVar"].

A variable is declared by either assigning a value to it, or by using the keyword var.

One case where it's useful to refer to a global variable as window.myVar is if you're inside a function that has a local variable called myvar. In that case, myVar refers to the local variable, while window.myVar refers to the global variable.

window.variableName means that the variable is being declared at the global scope. This means any JS code will have access to this variable.

Using window. is not necessary but is frequently used as a convention to denote that a variable is global.

Globals are generally to be avoided. You should define variables within the scope of functions.

您应该在var window.comment_id = ...省略单词var

Comments of @ CertainPerformance and @Li357 perfectly described:

You cannot declare a variable that's a property of another with var. Simply assign to the dot property instead

you can access directly or use window.Variableanme

JavaScript has two scopes – global and local. Any variable declared outside of a function belongs to the global scope, and is therefore accessible from anywhere in your code. Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions. Because local scope in JavaScript is created by functions, it's also called function scope. When we put a function inside another function, then we create nested scope.

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