javascript——函数属性和方法

 1 <script type="text/javascript">
 2         //每个函数都包含两个属性:length 和 prototype
 3         //length:当前函数希望接受的命名参数的个数
 4         //prototype:是保存他们所有实力方法的真正所在
 5 
 6 
 7         function sayName(name) {
 8             alert(name);
 9         }
10 
11 
12         function sum(num1, num2) {
13             return num1 + num2;
14         }
15 
16         function sayHi() {
17             alert("hi");
18         }
19 
20         alert(sayName.length);//1 参数个数一个
21         alert(sum.length);//2 参数个数2个
22         alert(sayHi.length);//0 没有参数
23 
24 
25         //每个函数都包含两个非继承而来的方法:apply() 和 call()
26         //这两个方法都是在特定的作用域中调用函数,实际上等于设置函数体内this对象的值
27         //首先apply()接受两个参数:一个是函数运行的作用域,另一个参数数组(可以是数组实例也可以是arguments对象)
28         function sum(num1, num2) {
29             return num1 + num2;
30         }
31 
32         function callSum1(num1, num2) {
33             return sum.apply(this, arguments);//传入arguments对象
34         }
35 
36         function callSum2(num1, num2) {
37             return sum.apply(this, [num1, num2]);
38         }
39 
40         alert(callSum1(10, 10));//20
41         alert(callSum2(10, 20));//30
42 
43 
44         //其次,call方法第一个参数没有变化,变化的是其余的参数都是传递参数,传递给函数的参数需要逐个列举出来
45         function sum(num1, num2) {
46             return num1 + num2;
47         }
48 
49         function callSum(num1, num2) {
50             return sum.call(this, num1, num2);
51         }
52 
53         alert(callSum(10, 200));
54         //至于使用哪个方法更方便,完全取决于你的意愿。如果没有参数,用哪个都一样。
55         //但是,apply和call方法的出现绝对不是只是为了怎样去船体参数。
56         //它们真正的用武之地在于扩充函数赖以运行的作用域。
57 
58         window.color = "red";
59         var o = {color: "blue"};
60         function sayColor() {
61             alert(this.color);
62         }
63         sayColor();//red
64 
65 
66         sayColor.call(this);//red
67         sayColor.call(window);//red
68         sayColor.call(o);//blue
69         //使用apply和call来扩充作用域的最大的好处就是不需要与方法有任何的耦合关系。
70 
71 
72         //ECMAScript5 还定义了一个方法:bind()。这个方法会创建一个函数的实例,其this值会被绑定到传给bind函数的值
73         window.color = "red";
74         var o = {color: "blue"};
75         function sayColor() {
76             alert(this.color);
77         }
78         var bindFun = sayColor.bind(o);
79         bindFun();//blue
80 
81     </script>