码迷,mamicode.com
首页 > Web开发 > 详细

js中的with语句

时间:2014-12-14 17:01:08      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   for   

  javascript中的with语句是什么?

        with 语句可以方便地用来引用某个特定对象中已有的属性,但是不能用来给对象添加属性。要给对象创建新的属性,必须明确地引用该对象。  

  

  看起来不懂吗?

 

<!DOCTYPE html>
<html>
<head>
    <title>with语句</title>
</head>
<body>

<div id="div0" onclick="a = 1">div</div>
<script>
    var eDiv = document.getElementById("div0");
    eDiv.a = 0;
    //因为eDiv下没有b这个属性, 所以b的值变成了window下的属性, 这个没有问题
    with(eDiv) {
        b = 0;
    };

    var obj = {
        c : 2
    };
    //因为obj下有c属性, 当我们设置值的时候, c会变成设置obj的c属性;
    with(obj){
        console.log(c);
        c = 0;
    };
    //输出 obj =  { c : 0 }
    console.log(obj);
</script>

</body>
</html>

 

 

  好吧, 我懂了,但是这个with有毛用呢(要特别注意with语句的花括号里面的语句跟this不一样的)?

  

<!DOCTYPE html>
<html>
<head>
    <title>with语句</title>
</head>
<body>

<script>
    window.l = function(){console.log( arguments[0] )};
    with(location) {
        l(hostname);
        l(href)
    };

</script>
</body>
</html>

 

  呵呵 ,好像就是少写几个代码的意思么么哒;

  (少年, 你好像知道的太多了哦);bubuko.com,布布扣

 

 

  说这个有毛用啊, 有没有干货,你这个搞毛的干活, 浪费我的时间呢, 混蛋。

  

<!DOCTYPE html>
<html>
<head>
    <title>with语句</title>
</head>
<body>

<input id="ipt0" value="111" onclick="console.log(value+attributes.hehe.value)" hehe="aiyobucuoo" />
<!--输出了 ==>> 111aiyobucuoo  --> 卧槽,这个是怎么回事, 没有用到this为什么可以把value直接输出出来啦;
</body>
</html>

  js内部对写在行内的onclick处理成了

  function(){

    with(document){

      with(this){

        //代码;

      }

    }

  }

  情不自禁的感叹,  又长见识了

  然后呢?

<!DOCTYPE html>
<html>
<head>
    <title>with语句</title>
</head>
<body>
<script>
    document.c = "dasb";
</script>
<form>
    <input value="1" type="text" name="xx" />
    <input value="2" type="text" name="age"/>
    <!---这里扩展了自己的作用域
        form的作用域
        以及documen的作用域
    ---->
    点击弹出clickMe12dasb
    <input type="button" value="clickMe" onclick="alert(value+age.value+xx.value+c)" />
</form>

<script>
    /*form扩展的作用域的方式可以看成是;
    with(document){
        with(this.form){
            with(this){

            }
        }
    }
    */
</script>
</body>
</html>

 

  懂了没:略懂略懂....

js中的with语句

标签:style   blog   http   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/diligenceday/p/4162687.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!