Function
- 本质上是对象,即函数名就是指针
- 定义方法:
(函数声明和函数表达式的区别在于,函数声明会被编译器提前放在源码树的底部,可在任意地方调用,而函数表达式只有在执行时才真正定义,在Safari中函数表达式可能会导致崔武)
- 函数声明:
function sum(num1,num2){ return sum1+sum2; }
函数表达式:var sum = function(sum1,sum2){ return sum1+sum2; }
- var sum = new Function("sum1","sum2","return sum1+sum2");
- 没有重载:因为本质上是指针,后面的覆盖前面的
- 作为值的函数,调用时不用在函数名后加(),因为并不是执行,是按参数传递
- 函数内部属性:
- arguments:记录函数的参数,还有一个callee属性指向该函数本身
- this:指向函数据以执行的环境变量
- rguments.callee.caller:保存着调用当前函数的函数引用,如果在全局作用域中调用函数,caller=null,与arguments.caller保存相同内容,严格模式下访问会出错,同时严格模式下不能为函数的caller赋值
- length:函数形参个数
- prototype:包含apply和call用于指定函数执行空间this
- apply接收两个参数:函数作用域和参数数组
- call方法需要把每一个参数列出:eg:sum.call(this,sum1,sum2);
- 用call来改变作用域:
- eg: var o ={color:"beautiful"};
- sum.call(o,2,6);
- bind:绑定执行环境并创建新的函数实例
- eg: var s = {color:'yellow'};
- var anotherSum = sum.bind(s);
- anotherSum(8,8);
- 函数的.toString() valoeof() toLocalString()都是简单的返回函数代码。
<!DOCTYPE html>
<html ng-app="ylApp">
<head lang="zh">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<title>javascript编程技术</title>
</head>
<body>
<script>
//----------------------------------------arguments.callee 的应用
function jiecheng(num){
if(num<=1){
return num;
}
else{
return num * arguments.callee(num-1);
}
}
console.log(jiecheng(4));
//-------------------------------------------------------this,
// 请注意即使在不同的环境中执行,o.sayColor指向的函数与sayColor()相同,
// 区别在于绑定的当前执行环境this不同。
window.color = "red";
sayColor = function(){
console.log(this.color);
};
sayColor();
var o ={color:'blue'};
o.sayColor = sayColor;
o.sayColor();
//------------------------------------------------------------caller
function outer(){
console.log("outer caller : " + arguments.callee.caller);
inner();
}
function inner(){
console.log("inner caller : " + arguments.callee.caller);
}
outer();
//----------------------------------------------arguments 和 length
function colors(col1,col2,col3){
console.log('give me ' + arguments.length);
}
console.log('colors needs ' + colors.length);
colors('red','pink');
//---------------------------------------------------apply()
function sum(sum1,sum2){
console.log("this 的 color : " + this.color); //red
return sum1 + sum2;
}
function callSum(sum1,sum3){
var color = "doublePink";
//这里面this的作用域是全局,所以输出是red而不是之前定义的doublePink
return sum.apply(this,arguments);
}
callSum(1,5);
//--用call或者apply来改变作用域
var o ={color:"beautiful"};
sum.call(o,2,6);
//或者sum.apply(0,[2,6]);
//-------------------------------------------------------bind(),
// -----------------------创建一个新的函数实例,并绑定执行环境
var s = {color:'yellow'};
var anotherSum = sum.bind(s);
anotherSum(8,8);
</script>
</body>
</html>