JS with理解和用法

来源:互联网 发布:百安居建材 知乎 编辑:程序博客网 时间:2024/05/01 00:09
  1. with(Math) {   
  2.      alert(E); // 得到结果就是Math.E的结果   
  3. }   
  4. // 如果在外部使用   
  5. alert(E); // 不是Math中的E   
  6. // 根据 https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Statements:with 中的解释   
  7.   
  8. with(arg) {   
  9.      statement   
  10. }   
  11. // arg在执行参数体的时候js通过with将arg加入大括号的作用域链中,让statement可以访问到arg,如上边的例子这样如果用户访问Math中的属性和方法的时候就可以直接写方法和属性名,就像window的全局属性和方法一样直接使用,省略前边的对象   
  12.   
  13. // 一段伪代码   
  14. eg:   
  15. var obj = {E : "hello"};   
  16. with(Math) {   
  17.      alert(E);   
  18.      with(obj)  {   
  19.           alert(E);   
  20.      }   
  21. }   
  22. // 如果with嵌套使用就是按照作用域的顺序  
原创粉丝点击