JavaScript try...catch for defineProperty not working

JavaScript try...catch for defineProperty not working

本文关键字:not working defineProperty for try catch JavaScript      更新时间:2023-09-26

我想知道为什么当我使用get()set()Object.defineProperty()方法时,捕获块内不会产生错误?

    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"

创建一个引用在创建函数时不是不可解析的符号的函数不是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函数时不是不可解析的。

来自@ t.j.的影响。克劳德的回答是,如果你想尝试捕获这个错误,你应该修改你的代码,如下所示;

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;