![](/img/trans.png)
[英]'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.