The JavaScript window object - the troublemaker

window object


JavaScript has a global object, that is window, which can bind all your custom variables and functions, including system default functions, such as alert(), let’s take a brief look at the functions of window (the window in this article is only used as a global object , do not introduce the window in the BOM)

function func8(){
    
    
    console.log("Hello world!");
}

var new_func8 = window.func4;
new_func8();					//输出 Hello world!

You can see that our custom function is directly assigned to new_func4. In the future, we use new_func4 which is equivalent to using func4(). Another example:

window.alert = function () {
    
    
    console.log("I'am alert function!");
}

alert();						//I'am alert function!

We directly killed the system function alert()!



Since window can represent any of our variables, it is easy to cause conflicts. For example, two programmers write two functions with the same name at the same time, and they are both bound to window. When they are finally combined, which function should window call?

//第一个 JS 文件
function func9() {
    
    
    console.log("Hello Python!");
}
//第二个 JS 文件
function func9() {
    
    
    console.log("Hello Java!");
}
<!-- 测试用的 HTML 文件 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>函数</title>
    <script src="JS/function.js"></script>
    <script src="JS/function2.js"></script>
    <script>
        window.func9();
    </script>
</head>
<body>


</body>
</html>

Console output:

29

The output depends entirely on the mood of the program.



To avoid this confusing behavior, we strongly recommend using custom global variables!

var MyWindow = [];				//定义一个全局变量(写在函数外,并用 var 声明的就是全局变量,不要忘了哦)

//以后将本文件所有的函数、变量都绑定到 MyWindow 上面
MyWindow.func10 = function () {
    
    
    console.log("I'am func1");
}

//将变量绑定到我们自定义的全局对象中
MyWindow.name = "Mike";

Guess you like

Origin blog.csdn.net/qq_52174675/article/details/122647622