您的位置:首页 > Web前端 > JavaScript

Javascript学习5 - 函数

2009-09-29 13:12 316 查看
在Javascript中,函数和对象是交织在一起的。有些函数的特性与对象相关联。这一点的内容在第六部分会讨论到。
这一部分主要讨论函数与其它比较熟悉的语言(如C/C++)不同的地方

5.1 函数定义
function 函数名(参数1,参数2...)
{
主体;
}
函数内可以有return,也可以没有return. 没有return时,函数返回undefined值。
另外,Javascript是类型宽松的语言,所以,对于函数调用时传递参数,有以下特性:
① Javascript不会检测传递的数据是不是函数要求的类型。
如果参数的数据类型很重要,可以在函数内用typeof运算符进行检测
② Javascript不会检测传递给它的参数是否正确。
如果传递的参数比需求的个数多,多余的值被忽略。
如果传递的参数比需求的个数少,所忽略的几个参数被赋于undefined值
③ 函数内部有个Arguments对象维护着实际传递给函数的参数。
用它可以实现得到实际传递给函数的参数个数,及参数值。用于实现可变参数函数。

5.2 嵌套函数
实现如下:

var a = square(4); // a contains the number 16
var b = square; // Now b refers to the same function that square does

例2:存储在对象的属性或数组元素中

var o = new Object;
y = o.square(16);
var a = new Array(3);
calculator.compute(); // What is 1+1?
print(calculator.result); // Display the result
以上,this关键字很重要,任何作方法的函数都被有效的传递了一个隐式的参数,即调用函数的对象(this).

5.6 函数的属性和方法
函数是Javascript对象的一种特殊类型,typeof运算符用于函数类型时会返回字符串“function”
既然函数是对象,它就具有属性和方法,就像其它的对象一样。
● 属性lenght
不同于函数体内arguments的length属性,函数自身的length属性是一个只读属性,返回的是函数需要的实际参数数目。
● 定义函数自身的属性,具有static属性

1// Create and initialize the "static" variable.
2// Function declarations are processed before code is executed, so
3// we really can do this assignment before the function declaration.
4uniqueInteger.counter = 0;
5
6// Here's the function. It returns a different value each time
7// it is called and uses a "static" property of itself to keep track
8// of the last value it returned.
9function uniqueInteger() {
return uniqueInteger.counter++; // Increment and return our "static" variable
}

● 方法 apply() 和 call()
这两个方法可以像调用其它方法一样调用函数。第一个参数都是要调用的函数对象,函数体内这一参数是关键字this的值。
call的剩余参数是传递给要调用的函数的值。
to the function f() and invoke it as if it were a method of the object o, you could use code like this:
f.call(o, 1, 2);
This is similar to the following lines of code:
o.m = f;
o.m(1,2);
delete o.m;
The apply() method is like the call() method, except that the arguments to be passed to the function are specified as an array:
f.apply(o, [1,2]);
For example, to find the largest number in an array of numbers, you could use the apply() method to pass the elements of the array to the Math.max() function:
var biggest = Math.max.apply(null, array_of_numbers);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: