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>

      运行结果为

  • 相关阅读:
    PHP之旅3 php数组以及遍历数组 以及each() list() foreach()
    NSSetUncaughtExceptionHandler
    runtime
    Objective-C中的instancetype和id区别
    tableView 局部刷新
    CGAffineTransform
    iOS中文本属性Attributes
    ios 相机 自定义 相片的截取
    php程序的生命周期
    PHP代码执行流程
  • 原文地址:https://www.cnblogs.com/xing901022/p/4282385.html
Copyright © 2011-2022 走看看