zoukankan      html  css  js  c++  java
  • js中的with语句

      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>

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

      (少年, 你好像知道的太多了哦);

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

      

    <!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>

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

  • 相关阅读:
    算法笔记 #003# 堆排序
    算法导论(第三版)练习 6.2-1 ~ 6.2-6
    Python开发【第六篇】:模块
    Python开发【第五篇】:Python基础之杂货铺
    Python开发【第四篇】:Python基础之函数
    Python开发【第三篇】:Python基本数据类型
    Python开发【第二篇】:初识Python
    python mysql
    跟着ttlsa一起学zabbix监控呗
    zabbix进程构成
  • 原文地址:https://www.cnblogs.com/diligenceday/p/4162687.html
Copyright © 2011-2022 走看看