search

Home  >  Q&A  >  body text

javascript function

function Foo(){
            getName = function(){
                console.log(1);
            };
           return this;
        }

        var getName = function (){ 
            console.log(4)
        };



          Foo().getName(); 

Why does the above code output 1;

After foo() is run, this is output. This is the window object. Does getName in foo() become a global function expression? And the following var getName is also a function expression; why is it printed? The result is 1;

foo, after execution, is it equivalent to the following code?

getName = function(){
            console.log(1);
        };

        var getName = function (){ 
            console.log(4)
        };



          getName(); //4
给我你的怀抱给我你的怀抱2713 days ago752

reply all(6)I'll reply

  • 高洛峰

    高洛峰2017-06-26 10:55:22

    When Foo is not called

    window.getName = function(){
        console.log(4);
    }
    

    When calling Foo()

    getName = function(){
                    console.log(1);
                };
    // 相当于更改了 window.getName

    After the call, return this in Foo does point to window, so the final result is 1.

    reply
    0
  • 扔个三星炸死你

    扔个三星炸死你2017-06-26 10:55:22

    function Foo(){
        getName = function(){
            console.log(1);
        };
        return this;
    }
    //全局声明一个变量getName
    var getName = function (){ 
        console.log(4)
    };
    //重新赋值
    getName = function () {
        console.log(1)
    }
    //最终打印结果为1
    window.getName()

    reply
    0
  • 黄舟

    黄舟2017-06-26 10:55:22

    Foo().getName(); executes getName in Foo

    reply
    0
  • 阿神

    阿神2017-06-26 10:55:22

    function Foo(){
        getName = function(){
            console.log(1);
        };
        return this;
    }
    
    var getName = function (){ 
        console.log(4)
    };
    
    Foo().getName();
    function Foo(){
        getName = function(){
            console.log(1);
        };
        return this;
    }
    
    var getName = function (){ 
        console.log(4)
    };
    
    getName = function () {
        console.log(1)
    }
    
    window.getName()

    reply
    0
  • 代言

    代言2017-06-26 10:55:22

    Check console.log(Foo()), are you sure it is window?

    reply
    0
  • ringa_lee

    ringa_lee2017-06-26 10:55:22

    The getName in the Foo function is not declared with var, so it is global, so when Foo is run, the getName function inside the function will overwrite the one defined outside

    reply
    0
  • Cancelreply