JavaScript try...catch for defineProperty not working
JavaScript try...catch for defineProperty not working
我想知道为什么当我使用get()
和set()
的Object.defineProperty()
方法时,捕获块内不会产生错误?
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
。错误发生在之后,当调用函数时,如果符号当时是不可解析的
考虑一下,例如,您可以这样做:
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
函数时不是不可解析的。
来自@ t.j.的影响。克劳德的回答是,如果你想尝试捕获这个错误,你应该修改你的代码,如下所示;
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;
相关文章:
- $rootScope not working
- jQuery document.ready not working
- Javascript getElementsByTagName not working?
- JQuery.val( ) not working
- Tomcat websocket is not working
- Javascript JSON.parse not working
- NodeJS Multer is not working
- Regex not working
- Ember run.debounce not working
- AngularJs 1 not working
- document.getElementById.style.backgroundImage not working
- Rxjs5, distinct() is not working
- createOscillator noteOn not working
- Javascript - .getHours() not working
- Javascript setTimeout not working | onkeydown
- MongoDB $pull not working
- Express router.use not working
- JSONP not working
- window.opener not working in chrome & IE
- Backbone + RequireJS: Collection.each() is not working