JavaScript引用数据类型之Function类型:创建函数、函数内部属性、函数的属性和方法等

JavaScript引用数据类型之Function类型

(1)创建函数

var add = function(x,y){
    
    
  return x+y;
};
console.log(add(10,10));//20

(2)js函数没有重载

function sum(x,y){
    
    
  return x+y+',执行函数1。。。。';
}

function sum(x,y){
    
    
  return x+y+',执行函数2。。。。';
}
console.log(sum(10,10));       //20,执行函数2。。。。

(3)作为值的函数

function callSomeFunction(someFunction,someArg){
    
    
  return someFunction(someArg)       //返回一个函数和参数add10(20)
}
function add10(num){
    
    
  return num+10;
}
console.log(callSomeFunction(add10,20));   //函数add10()作为参数传入callSomeFunction()

(4)函数内部属性:arguments、this、caller

1、arguments: 保存参数,arguments是类数组对象,它的属性callee是一个指针,指向拥有这个arguments对象的函数,即f()

function f(num){
    
    
  if(num<=1) return 1;
  else return num*arguments.callee(num-1);  
}
console.log(f(5));//120  

5f(4)=54f(3)=543f(2)=5432f(1)=54322*1=120

2、this

window.color = 'red'
var obj = {
    
    color:'blue'}
function sayColor(){
    
    
  console.log(this);
}
sayColor();                //this是widow全局对象 
obj.sayColor = sayColor;
obj.sayColor();            //this是对象obj的执行环境对象

3、caller:存着调用当前函数的函数的引用(调用本函数的函数)

function outer(){
    
    
  inner();
}
function inner(){
    
    
  console.log(inner.caller);//ƒ outer() {inner();}
  console.log(arguments.callee.caller);//访问相同信息   ƒ outer() {inner();}
}
outer();

(5)函数的属性: length、prototype

1、length:函数希望接收的命名参数个数

console.log(sum.length);

2、prototype:保存所有实例方法的真正所在,在E5不可枚举,因此使用for-in无法发现

console.log(sum.prototype);

(6)函数的方法:apply()、call()、bind()

设置函数体内对象的值(改变函数体内部this的指向)

1、apply() 传入参数:this+参数数组

function callSum1(n1,n2){
    
    
  return sum.apply(this,arguments);
}
function callSum2(n1,n2){
    
    
  return sum.apply(this,[n1,n2]);
}

2、call() 传入参数:this+多个参数值

function callSum3(n1,n2){
    
    
  return sum.call(this,n1,n2)
}
function callSum4(n1,n2){
    
    
  return sum.cal(this,arguments[0],arguments[1])
}
console.log(callSum1(10,20));   
console.log(callSum2(20,20));    
console.log(callSum3(10,40));    
console.log(callSum4(20,40));    

3、bind() 传入参数:指定绑定函数的this值

window.color = 'red'
var obj = {
    
    color:'blue',name:'HNN'}
function sayColor(){
    
    
  console.log(this.color);
}

var objSayColor = sayColor.bind(obj)   //绑定函数的this值为obj后执行  <==> sayColor.bind(obj)()
objSayColor()              //blue    this=>obj
sayColor()                 //red     this=>window

4、作用:扩充函数赖以运行的作用域

function People(name,age){
    
    
  this.name = name;
  this.age = age;
  console.log(this);
}
function Student(name,age,grade){
    
    
  People.call(this,name,age)      //this代表Student,使用Student调用People中的方法,将name,age参数传过去
  this.grade = grade;
  console.log(this);
}
var stu = new Student('小明',18,'大三');
console.log(stu.name+","+stu.age+","+stu.grade);//小明,18,大三

猜你喜欢

转载自blog.csdn.net/m0_47147246/article/details/125731949