开发者

How to declare global var in javascript and HTML?

How to declare a variable, I think global开发者_开发知识库, the way I declare in an html file and then use it in a js file (included by <script> tags)?


You can assign to the window object, i.e. window.myGlobal = 3;. window is the default context for variable binding. That's why you can reference document instead of needing to do a window.document.

But yeah as David says, you should avoid using globals. And if you are going to use globals, you should place them and other top-level declarations in a "namespace" object to avoid potential naming collisions with other libraries, like this:

myNamespace = { myGlobal: 3 };

// Then to access...
myNamespace.myGlobal = 6;


Don't use the var keyword

(That said, globals are usually the wrong solution to any given problem in JS)


So as I understand, you want to use a variable from an HTML file in a JS file? To pass a variable from an HTML file to a javascript file, pass it with a function:

HTML.html

    <a href="#" onClick="test('John Doe')">Send Name</a>

Javascript.js

function test(full_name) {
 alert(full_name);
}


Please, avoid using global variables.

To answer your question, there are two ways of declaring a global variable in JavaScript. You can either omit the 'var' keyword, or declare the variable outside any function.

In this code sample, both thisIsGlobal and thisIsAlsoGlobal are global variables and set to null.

var thisIsGlobal= null;
function foo() {
    thisIsAlsoGlobal = null;
    // code goes here
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜