[英]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()
? 我想知道为什么当我使用带有get()
和set()
Object.defineProperty()
方法时,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"
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. 创建一个ReferenceError
在创建函数时不可解析的符号的函数不是ReferenceError
。 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. 记录"Hi there"
因为fxxxxx
在调用get
函数时不可解析。
Influencing from @TJ Crowder's answer, if you would like to try to catch that error you should change your code as follows; 受@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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.