How does Javascript execute code when duplicate named functions are declared?

后端 未结 2 409
野的像风
野的像风 2021-01-24 19:47

I\'m trying to understand why declaring a duplicate function after a statement has executed affects it.

It\'s as if JavaScript is reading ALL functions first,

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 20:04

    In Javascript, if you define two functions with the same name, then the last one parsed is the one that will be active after parsing. The first one will be replaced by the second one and there will be no way to reach the first one.

    Also, keep in mind that all function() {} definitions within a scope are hoisted to the top of the scope and are processed before any code in that scope executes so in your example, if you uncomment the second definition, it will be the operative definition for the entire scope and thus your var tony = new Question('Stack','Overflow'); statement will use the 2nd definition which is why it won't have a .getAnswer() method.

    So, code like this:

    function Question(x, y) {
       this.getAnswer = function() {
      return 42;
      };
    };
    
    var tony = new Question('Stack','Overflow');
    console.log(tony.getAnswer());
    
    // If the following 2 lines are uncommented, I get an error:
    function Question(x, y) { 
    };
    

    Works like this because of hoisting:

    function Question(x, y) {
       this.getAnswer = function() {
      return 42;
      };
    };
    
    // If the following 2 lines are uncommented, I get an error:
    function Question(x, y) { 
    };
    
    var tony = new Question('Stack','Overflow');
    console.log(tony.getAnswer());    // error
    

提交回复
热议问题