4

I'd like to know why the error is not raised inside the catch block when i use Object.defineProperty() method with get() and 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"
poro6
  • 43
  • 5

2 Answers2

4

It's not a ReferenceError to create a function that refers to a symbol that isn't unresolvable at the time the function is created. The error happens later, when the function is called, if the symbol is unresolvable at that time.

Consider, for instance, that you could do this:

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();

That logs "Hi there" because fxxxxx isn't unresolvable as of when the get function is called.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @Crowder, @Bergi: thank you for your explaintation. Also, try/catch does the same behavior with code that is inside the `addEventListener` when error happens later. – poro6 Sep 17 '16 at 16:15
  • 1
    @poro6 Yes, it's the same for all function definitions. The exception is created when the function is called, not when it is created. Regardless whether that's a simple declaration, a getter (like in your question) or an event listener. – Bergi Sep 17 '16 at 16:20
  • @Bergi: this is a golden rule for me. Thanks for your input. – poro6 Sep 17 '16 at 16:29
1

Influencing from @T.J. Crowder's answer, if you would like to try to catch that error you should change your code as follows;

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

a = function() {
  return true;
}
window.a;
Redu
  • 25,060
  • 6
  • 56
  • 76