首页 > 技术文章 > js中的函数易忽略的点小节

yangxiaoguai132 2016-03-30 09:46 原文

1.Function()属性和方法

属性:

prototype

 

2.Function对象实例属性和方法

实例属性:(例如var Function=function(x,y,z){}; myFunction.length;)

  • arguments
  • constructor
  • length

实例方法(例如var myFunction=function(x,y,z){}; myFunction.toString();)

  • apply()
  • call()
  • toString()

 

3.函数总有返回值

例如:

1 var sayHi=function(){
2    return "hi";
3 };
4 
5 console.log(sayHi());//返回值为hi

 如果没有指定返回值,则会返回undefined。下面调用yelp函数,将字符串yelp返回控制台,且不会显式返回值。

1 var yelp=function(){
2    console.log("yeklp");
3 }
4 console.log(yelp()===undefined);//true

 虽然没有显示的return返回值,但还是有返回值存在的,如果不指定要返回的值,则返回是undefined

 

4.函数为什么被称为是“一等公民”

  • 函数是对象,可以存储在一个变量、数组或对象中
  • 函数可以传递给函数,并由函数返回。函数拥有属性,因为他是一个对象

 

 

5.arguments对象的length属性:调用时发送给函数的参数数量,例如:

1 var myFunction=function(z,s,d){
2     return arguments.length;
3 };
4 console.log(myFunction());//0

Function()实例的length属性:函数所需要的参数总数量,例如:

1 var myFunction=function(z,s,d){
2     return myFunction.length;
3 }
4 console.log(myFunction());//3

 

6.定义函数的四种方式:

//函数的构造函数:

var addConstructor=new Function('x','y','return x+y');

//函数声明

function foo(x,y){

   return x+y;

}

//函数表达式

var foo=function(x,y){

   return x+y;

}

//函数声明表达式

var foo=function add(x,y){

   return x+y;

};

 

 

 

7.调用函数的方式:

//函数模式

1 var foo=function(){
2  return "foo";
3 }
4 console.log(foo());

//方法模式

1 var myObject={
2     myFunction:function(){
3              return "bar";
4 }
5 }
6 console.log(myObject.myFunction());

//构造函数模式

1 var Cody=function(){
2      this.living=true;
3      this.foo=function(){
4           return this.living;
5 };
6 }
7 var cody=new Cody();
8 console.log(cody);

//apply和call模式

 1 var great={
 2      runGreet:function(){
 3          console.log(this.name,arguments[0],arguments[1]);
 4 }
 5 }
 6 
 7 var cody={name:'cody'};
 8 var lisa={name:'lisa'};
 9 
10 greet.runGreet.call(cody,'foo','bar');// cody foo bar
11 greet.runGreet.apply(lisa,['foo','bar']);//lisa foo bar

 

 

8.自定义的匿名函数语句

 1 (function(msg){
 2    console.log(msg);
 3 })("Hi");
 4 
 5 
 6 (function(msg){
 7     console.log(msg);
 8 }("Hi"));
 9 
10 
11 !function(msg){
12     console.log(msg);
13 }("Hi");
14 
15 
16 //以下代码不行
17 function sayHi(){
18     console.log("hi");
19 }();

 

推荐阅读