`
hlbng
  • 浏览: 175600 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

JS中with的用法

阅读更多

进来在看到在js中使用with,实话我以前从来没有碰到过。

eg:

Js代码 复制代码
  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嵌套使用就是按照作用域的顺序  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics