---
title: "javascrip Function"
author: "demojava"
date: "2012-02-04T11:48:51Z"
tags: []
categories: ["Web前端"]
slug: "javascrip-function"
draft: false
lastmod: "2012-04-02T13:50:10Z"
id: 1392657
url: "https://demojava.iteye.com/blog/1392657"
---

javascript函数  
在javascirpt 1.1中除了可以使用 function 语句定义函数之外,还可以使用Function()构造函数来定义函数，  
var 函数名=new Function("参数1","参数2","参数3"....."函数体");  
var myfun=new Function("x","y","return x+y ;");  
var myfun=new Function("x","y","var num=x+y;return num;");  
上面代码使用Function()构造函数定义了一个名为 myfun 的函数，  
function myfun(x,y)  
{  
return x+y;  
}  
使用Function()构造函数和使用function语句的区别：  
1.使用Function()构造函数可以动态定义和编译,而function语句只能预编译，因此所在每次调用使用Function()  
函数是需要经常使用的函数应该避免使用Function来定义函数  
2.使用Funciton()构造函数定义函数时，可以将函数的定义写成表达式，而使用Function的语句就是语句块  
3.使用Funciton()构造函数可以在一个表达式中定义函数，而funciton语句就不能。

```
function myfun(x,y)
{
 if(typeof(x)=="number"&&typeof(y)=="number")
 {
  var z=x*y;
  return z;
 }else
 {
  return "传入参数不正确";
 }
}
```

 

在JavaScirpt中提供了一个Arguments对象，该对象可以获取从javascirpt函数中传过来的参数，并  
净这些参数放在argu  
ments\[]数组中，  
function mufun(x,y)  
{  
 if(arguments.length!=2) return "参数不正确";  
 //arguments\[0];是函数的第一个参数  
}

caller属性：判断函数调用情况

```
// caller demo { 
function callerDemo() { 
    if (callerDemo.caller) { 
        var a= callerDemo.caller.toString(); 
        alert(a); 
    } else { 
        alert("this is a top function"); 
    } 
} 
function handleCaller() { 
    callerDemo(); 
}

```

   
系统函数  
1.编码函数escape("abc!#$%");将字符串中的非文字，数字的字符转换成相应的ASCII码值。  
2.解码函数unescape();是将ASII码的文字转换成一般的文字和 escape();功能相反

3.系统函数 call 和 apply使用如下：

```
 function MyClass(){
   
}
MyClass.prototype.addAge(a,b){
   return a+b;
};

var myclass = new MyClass();
var fun = myclass.addAge;
//call
func.call(myclass,5,6);//this or obj, 参数1，参数2，参数3。。。

//apply
func.apply(myclass,[5,6]);//this or obj, 然后数组[]
```