---
title: "JS中with的用法"
author: "hlbng"
date: "2009-05-08T16:22:20Z"
tags: []
slug: "js-with"
draft: false
lastmod: "2009-05-08T16:22:20Z"
id: 382182
url: "https://hlbng.iteye.com/blog/382182"
---

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

eg:

Js代码 [![复制代码](http://lovezzy.iteye.com/images/icon_copy.gif)](http://lovezzy.iteye.com/blog/272210 "复制代码")

01. **with**(Math) {
02. alert(E); // 得到结果就是Math.E的结果
03. }
04. // 如果在外部使用
05. alert(E); // 不是Math中的E
06. // 根据 https://developer.mozilla.org/En/Core\_JavaScript\_1.5\_Reference:Statements:with 中的解释
07. **with**(arg) {
08. statement
09. }
10. // arg在执行参数体的时候js通过with将arg加入大括号的作用域链中,让statement可以访问到arg,如上边的例子这样如果用户访问Math中的属性和方法的时候就可以直接写方法和属性名,就像window的全局属性和方法一样直接使用，省略前边的对象
11. // 一段伪代码
12. eg:
13. **var** obj = {E : "hello"};
14. **with**(Math) {
15. alert(E);
16. **with**(obj)  {
17. alert(E);
18. }
19. }
20. // 如果with嵌套使用就是按照作用域的顺序