Search code examples
javascripttry-catchgetter-setterdefineproperty

JavaScript try...catch for defineProperty not working


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"


Solution

  • 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.