【问题标题】:How does Javascript execute code when duplicate named functions are declared?声明重复的命名函数时,Javascript 如何执行代码?
【发布时间】:2015-07-30 02:32:59
【问题描述】:

我试图理解为什么声明重复函数语句执行后会影响它。

就好像 JavaScript 首先读取所有函数,不管放置/控制流,然后执行console.log 表达式。示例:

function Question(x, y) {
   this.getAnswer = function() {
  return 42;
  };
};

var tony = new Question('Stack','Overflow');
console.log(tony.getAnswer());   // 42, as expected.

// If the following 2 lines are uncommented, I get an error:
// function Question(x, y) { 
// };

错误是:

未捕获的类型错误:tony.getAnswer 不是函数

但是当 JavaScript 运行 console.log 语句时,它如何知道它还不是一个函数,因为 Person 类直到 console.log 之后的行 才会被覆盖?

【问题讨论】:

    标签: javascript object


    【解决方案1】:

    在Javascript中,如果你定义了两个同名的函数,那么最后解析的就是解析后激活的那个。第一个将被第二个替换,并且无法到达第一个。

    另外,请记住,范围内的所有 function() {} 定义都被提升到范围的顶部,并在该范围内的任何代码执行之前进行处理,因此在您的示例中,如果您取消注释第二个定义,它将是整个范围的操作定义,因此您的 var tony = new Question('Stack','Overflow'); 语句将使用第二个定义,这就是它没有 .getAnswer() 方法的原因。

    所以,代码如下:

    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) { 
    };
    

    因为吊装,所以这样工作:

    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
    

    【讨论】:

      【解决方案2】:

      它被称为提升,所有声明性函数和变量声明在编译时都会上移,尽管未定义。

      http://code.tutsplus.com/tutorials/javascript-hoisting-explained--net-15092

      http://bonsaiden.github.io/JavaScript-Garden/#function.scopes

      声明性函数是像

      这样的函数

      function name(){...}

      【讨论】:

        猜你喜欢
        • 2012-06-17
        • 2015-03-27
        • 1970-01-01
        • 1970-01-01
        • 2010-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-22
        相关资源
        最近更新 更多