【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>
复制代码

  运行结果为

posted @   xingoo  阅读(938)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示