[英]'try' 'catch' is not working in this JavaScript code
[英]JavaScript try…catch for defineProperty not working
我想知道为什么当我使用带有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"
创建一个ReferenceError
在创建函数时不可解析的符号的函数不是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
函数时不可解析。
受@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.