javascript核心 -- function
1. 调用 1.1 函数调用
function f(){
// TODO xxxx
}
f();// 函数调用
1.2方法调用
var obj = {
m:function(){
// TODO xxxx
}
}
obj.m();
区别: 函数调用在ECMAScript3和非严格下的ECMAScript5调用的上下文是(this)全局对象,但是在严格模式下调用的上下文是undefined
方法调用上下文 this指向本身
eg
var obj = {
m:function(){
var self = this;
console.log(this === obj); // true
f();
function f(){
console.log(this === obj); //false;
console.log(this); // this 为undefined 或者为全局上下文对象
console.log(self === obj); // true
}
return this;
}
}
obj.m();
2. 传递参数 2.1 少传递 --> 变成undefined
function f(a,b,c){
console.log(a); // a = 1
console.log(b); // b = 2
console.log(c); // c = undefined
}
f(1,2);
2.2 多传递 --> 通过 arguments来获取
function f(a){
console.log(a); // 1
console.log(arguments.length); //2
console.log(arguments[0]); //1 == a
console.log(arguments[1]); //2 == 第二个参数
console.log(arguments[2]); //undefined
}
f(1,2);
注: arguments 并不是数组,只是碰巧用数字做索引,以及一个length属性
2.3. arguments的两个属性callee 与 caller
在非严格模式下,callee 指:当前正在执行的函数 caller 指:调用当前正在执行的函数的函数
var f = function(x){
if(x <=1){
return 1;
}
return x*arguments.callee(x-1);
}
f(5); // 进行递归调用 120
3. 做值的函数
function square(x){
return x*x;
}
var s = square;
square(4);//16
s(5); //25
/**
* a[0]: 是一个function
* a[1]: 20
*/
var a = [function square(x){return x*x;},20];
a[0](a[1]); //400
//操作数,function作为参数传递
function add(x,y){
return x+y;
}
function operate(operator,operand1,operand2){
return operator(operand1,operand2);
}
operate(add,1,2);