【Javascript】—— 1 方法function的高级特性

时间:2023-03-09 23:30:50
【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>

  运行结果为

【Javascript】—— 1 方法function的高级特性