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

Function类型大小事

2016-09-18 00:00 267 查看
摘要: 来自《javascript高级程序设计》。

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
/*1.函数是对象,函数名是指针*/
function sum(value1,value2){
return value1+value2;
}
console.log(sum(1,2));//3
var copySum=sum;
console.log(copySum(3,4))//7
sum=null;
console.log(copySum(5,6))//11

/*2.没有重载*/
function add(value1){
return value1+100;
}
function add(value1,value2){
return value1+value2;
}
console.log(add(1));//NaN
console.log(add(1,1));//2

/*3.函数内部特殊的对象:arguments和this.*/
function factorial(num){
if(num <= 1){
return 1;
}else{
return num * arguments.callee(num-1);//递归方式实现阶乘,arguments.callee执行拥有arguments这个对象的函数。消除耦合
}
}
console.log(factorial(1));//1
console.log(factorial(3));//6
console.log(factorial(4));//24

window.color="red";
var myColor={color:"blue"};
function sayColor(){
return this.color;//this
}
console.log(sayColor());//red
myColor.sayColor=sayColor;//引用
console.log(myColor.sayColor());//blue

/*4.caller*/
function outer(){
inner();
}
function inner(){
console.log(arguments.callee.caller);
}
outer();

/*5.函数的属性:length和prototype*/
console.log(outer.length)//0,length为函数期望接收到的参数的个数

/*6.函数的方法:call()和apply(),消除耦合*/
function subtraction(value1,value2){
return value1-value2;
}
function sub1(value1,value2){
return subtraction.apply(this,arguments);
}
function sub2(value1,value2){
return subtraction.apply(this,[value1,value2]);
}
function sub3(value1,value2){
return subtraction.apply(this,[50,8]);
}
console.log(sub1(5,2));//3
console.log(sub2(4,3));//1
console.log(sub3());//42
/*------------------------*/
function addFunction(a,b){
console.log(a+b);
}
function subFunction(a,b){
console.log(a-b);
}
addFunction.call(subFunction,3,1);//4
/*------------------------*/
function Animal(){
this.name = "Animal";
this.showName = function(){
console.log(this.name);
}
}
function Cat(){
this.name = "Cat";
}
var animal = new Animal();
var cat = new Cat();
animal.showName.call(cat,",");//Cat,通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。
animal.showName.apply(cat,[]);//Cat
</script>

<input type="text" id="myText"   value="input text">
<script>
function Obj(){this.value="对象!";}
var value="global 变量";
function Fun1(){alert(this.value);}

window.Fun1();   //global 变量
Fun1.call(window);  //global 变量
Fun1.call(document.getElementById('myText'));  //input text
Fun1.call(new Obj());   //对象!
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息