2016-09-17 18 views
4

我想知道为什么错误不会在catch块内部引发,当我使用Object.defineProperty()方法时get()set()JavaScript try ... catch for 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"

+0

谢谢你,克劳德。非常好的答案。 – poro6

+1

尽管如此,最好使用Stack Snippets('<>'工具栏按钮)来创建可运行的现场演示,而不是jsFiddle,这是不在现场的。 (我的答案有一个片段,所以你可以看到他们是什么样的。) –

+0

我会在下次做。谢谢。 – poro6

回答

4

这不是一个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函数被调用的。

+0

@Crowder,@Bergi:谢谢你的解释。此外,当稍后发生错误时,try/catch对'addEventListener'内的代码执行相同的行为。 – poro6

+1

@ poro6是的,所有函数定义都是一样的。当函数被调用时创建异常,而不是在创建时创建。无论这是一个简单的声明,一个getter(就像你的问题)或一个事件监听器。 – Bergi

+0

@Bergi:这对我来说是一条金科玉律。感谢您的输入。 – poro6

1

影响@ T.J. 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;

+1

感谢您的建议。我会这样做。 – poro6