zoukankan      html  css  js  c++  java
  • 【Javascript】—— 1 方法function的高级特性

      本篇仅仅对于function作简单的讲解,在javascript中function不仅仅是方法,它其实是一个变量,因此拥有自己的属性,并且可以当做参数传递给其他的方法。

      那么传统的方法,按照java的写法应该如下的创建:

    <!-- 普通的function -->
                function testFunc1(name,age){
                    console.log("name"+name+" age"+age);
                }
                testFunc1("xingoo",26);

      但是我们在javascript中也可以通过var声明变量的方式来创建,但是需要使用Function方法。

      Function方法,前几个参数是我们创建的方法的参数,最后一个是它的方法体。

                <!-- 通过创建变量方式,创建的function -->
                var testFunc2 = new Function("name","age","console.log('name'+name+' age'+age)");
                testFunc2("halo",25);

      方法还有几个比较常用的属性:

      length 参数的个数

      toString() 可以获取方法的源码,如果采用第二种方法创建的方法则方法名会以anonymous来代替。

      valueOf() 作用类似toString()

      下面看一下可以运行的代码:

    <!doctype html>
    <html>
        <head>
        </head>
        <body>
            <script type="text/javascript">
                <!-- 普通的function -->
                function testFunc1(name,age){
                    console.log("name"+name+" age"+age);
                }
                testFunc1("xingoo",26);
    
                <!-- 通过创建变量方式,创建的function -->
                var testFunc2 = new Function("name","age","console.log('name'+name+' age'+age)");
                testFunc2("halo",25);
    
                console.log(testFunc1.length);
                console.log(testFunc1.toString());
                console.log(testFunc2.toString());
                console.log(testFunc2.valueOf());
            </script>
        </body>
    </html>

      运行结果为

  • 相关阅读:
    如何使样式CSS不被覆盖 !important
    PHP5中数组函数总结篇
    优化php效率,提高php性能的一些方法
    windows2003 系统下不能识别移动硬盘解决方法
    Sql Server 2000索引问题?
    在网页中调用本地的应用程序
    Sql Server资料收集(摘自http://www.itpub.net)
    利用CSS控制打印
    C#.NET 中的类型转换
    卓越领导力素质训练心得
  • 原文地址:https://www.cnblogs.com/xing901022/p/4282385.html
Copyright © 2011-2022 走看看