4

我想知道当我使用andObject.defineProperty()方法时,为什么在 catch 块内没有引发错误?get()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"

4

2 回答 2

4

创建一个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

于 2016-09-17T15:43:42.730 回答
1

受@TJ 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;

于 2016-09-17T16:00:07.970 回答