About the call () method in js

if ("a" in window) {
    var a = 1;
    console.log(a)
}
console.log(a);
function a() {
    console.log(this);
}

a.call(null);

clipboard.png

I don"t understand why this error was reported. Ask for advice

Apr.07,2022

js the function declaration is promoted to the top during execution, so when you execute the if statement, a is replaced with a numeric type variable with a value of 1 , not a function type. You can read the following articles about variable promotion, such as https://juejin.im/post/59905b...


// 

        function a() {
            console.log(this);
        
        var a;
    
        if ("a" in window) {
            a = 1;
            console.log(a)
        }
        console.log(a);//a1 

        a.call(null);
        
        
         [https://segmentfault.com/a/1190000017805834][1]


your a.call () an is the basic type a = 1, not object, so it will report an error. Variable promotion is involved here. In js, the function is a first-class citizen, and the above code parses to:

 function a() {
   console.log(this);
}
var a;
if ("a" in window) {
    a = 1;
    console.log(a)
}
console.log(a);
a.call(null); 
Menu