4

Object.defineProperty()とでメソッドを使用するget()と、catch ブロック内でエラーが発生しない理由を知りたいset()ですか?

    try {
      var f;
      Object.defineProperty(window, 'a', {
        get: function() {
          return fxxxxx; // here: undef var but no error catched
        },
        set: function(v) {
          f = v;
        }
      });
    } catch (e) {
      console.log('try...catch OK: ', e);
    }
    
    a = function() {
      return true;
    }
    window.a();

    // Expected output: "try...catch OK: ReferenceError: fxxxxx is not defined"
    // Console output: "ReferenceError: fxxxxx is not defined"

4

2 に答える 2

4

関数のReferenceError作成時に解決できないシンボルを参照する関数を作成することはできません。その時点でシンボルが解決できない場合、関数が呼び出されたときにエラーが発生します。

たとえば、これを行うことができると考えてください:

try {
  var f;
  Object.defineProperty(window, 'a', {
    get: function() {
      return fxxxxx;
    },
    set: function(v) {
      f = v;
    }
  });
} catch (e) {
  console.log('try...catch OK: ', e);
}

window.fxxxxx = function() { console.log("Hi there"); };   // <====== Added this

a = function() {
  return true;
}
window.a();

関数が呼び出された時点で解決できない"Hi there"ため、ログに記録されます。fxxxxx get

于 2016-09-17T15:43:42.730 に答える