JavaScript try...catch for defineProperty 不工作

JavaScript try...catch for defineProperty not working

我想知道当我将 Object.defineProperty() 方法与 get()set() 一起使用时,为什么在 catch 块内没有出现错误?

    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。错误发生在later,调用函数时,if当时符号无法解析。

例如,考虑一下您可以这样做:

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的影响。 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;