2
function mymethod(){
  alert("global mymethod");
}

function mysecondmethod(){
  alert("global mysecondmethod");
}

function hoisting(){
  alert(typeof mymethod);
  alert(typeof mysecondmethod);

  mymethod();         // local mymethod
  mysecondmethod(); // TypeError: undefined is not a function

  // mymethod AND the implementation get hoisted
  function mymethod(){
    alert("local mymethod");  
}

// Only the variable mysecondmethod get's hoisted
var mysecondmethod = function() {
    alert("local mysecondmethod");  
};
}
hoisting();

この場合、巻き上げがどのように機能するのか、またalert("local mysecondmethod");表示されない理由がわかりません。誰か順番を教えてくれたら助かります

4

2 に答える 2

3

関数内でhoistingは、コードは次のように並べ替えられます。

function hoisting(){
  var mysecondmethod;

  function mymethod(){
    alert("local mymethod");  
  }

  alert(typeof mymethod);
  alert(typeof mysecondmethod);

  mymethod();
  mysecondmethod();


  mysecondmethod = function() {
    alert("local mysecondmethod");  
  };
}

mysecondmethodここで、関数のスコープ内に新しい変数を作成し、外部の定義をオーバーレイすることは明らかです。ただし、関数の呼び出し時点では、(まだ) 定義されていないため、エラーが発生します。

于 2013-04-25T12:31:00.300 に答える
1

巻き上げを理解する最も簡単な方法は、すべての var ステートメントを取得し、それらを含む関数の先頭に移動することです。

function hoisting(){
  var mysecondmethod; // locally undefined for now
  alert(typeof mymethod);
  alert(typeof mysecondmethod);

  mymethod();         // local mymethod
  mysecondmethod(); // TypeError: undefined is not a function

  // mymethod AND the implementation get hoisted
  function mymethod(){
    alert("local mymethod");  
  }

  // Only the variable mysecondmethod get's hoisted
  mysecondmethod = function() {
    alert("local mysecondmethod");  
  };
}
hoisting();
于 2013-04-25T12:29:55.470 に答える