JavaScript try ... catch for defineProperty not working

I would like to know why the error does not occur inside the catch block when I use the method Object.defineProperty()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"
Run codeHide result
+4
source share
2 answers

This is not ReferenceErrorto create a function that refers to a character that is not unsolvable at the time the function was created. The error is called later when the function is called if at that moment the character is unsolvable.

Consider, for example, 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();
Run codeHide result

logs "Hi there", fxxxxx get.

+4

@T.J. Crowder, , :

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;
Hide result
+1

Source: https://habr.com/ru/post/1654913/


All Articles