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()
?
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. 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.
Influencing from @TJ Crowder's answer, if you would like to try to catch that error you should change your code as follows;
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.