javascript函数基础--函数的调用模式(4种)

在Javascript中,公有4种函数调用模式:方法调用模式 、函数调用模式    、构造器调用模式、apply调用模式

这些模式在如何初始化this上存在差异

  1--方法调用模式   

  当一个函数被保存为对象的一个属性值 时,我们称之为一个方法,this被绑定在对象上

 var obj={

    value: 0,

   increment : function(inc){

                      this.value+=typeof inc==='number'?inc:1;

                  }

  }   

obj.increment();  console.log(obj.value)   //1

obj.increment(2);  console.log(obj.value)   //3

2--函数调用模式       

   当一个函数不是一个对象的属性时,它被当做函数来调用,his绑定到全局上

  var sum=add(3,4);  //this绑定到全局上

 var obj={

    value :1;

   doub:function(){

      var that=this;

      var helper=function(){ //this会绑定到全局,通过that来改变this的指向

           that.vaule=that.value*2;

          };

      helper();

     }

}

obj.doub();

document.writeln(obj.value);//2

3--构造器调用模式   

       如果在一个函数前面加上new运算符来进行调用,那么将创建一个隐藏的链接到该函数的prototype原型对象的新实例对象

同时this也会绑定到这个新实例对象上,注意new运算也会改变return的行为

 var  F=function(string){

      this.status=string;

    };

F.prototype.get=function(){

  return this.status;

  }

var f=new F('new object'); console.log(f.get()) //'new object'

  4--apply调用模式

javascript是函数式的面向对象编程语言,函数可以拥有方法,apply就是函数的一个基本方法,使用这个方法可以调用函数

var array=[5,4];

var add=function(){

  var i,sum=0;

 for(i=0;i<arguments.length;i+=1){

   sum+=arguments[i];

   }

 return sum;

}

var sum=add.apply({},array);//9

 var  F=function(string){

      this.status=string;

    };

F.prototype.get=function(){

  return this.status;

  }

var obj={

  status:'obj'

};

var status=F.prototype.get.apply(obj); //'obj'

猜你喜欢

转载自blog.csdn.net/wenmin1987/article/details/83930057