call()与apply() 改变this指向

 call

1、作用

调用函数并且改变this的指向

2、语法

函数名.call(thisArg,arg1,arg2...)

3、参数

   thisArg 函数中this指向的值

arg1,arg2... 从call里的第二个参数开始,都是真正函数里的参数

4返回值

undefined

 

注意:thisArg 的值为null或者undefined的时候,this是指向window

 

fn.call(1);                //this指向数字
fn.call('kaivon');        //this指向字符串
fn.call(true);            //this指向布尔值
fn.call([1,2,3]);         //this指向数组
fn.call({});              //this指向对象
fn.call(null);            //this指向window
fn.call(undefined);        //this指向window
function fn1(name,age){
    console.log(this,name,age);        
}
fn1.call(1,'kaivon',18);        //Number "kaivon" 18
fn1.call({a:10,b:20},'陈学辉',18);  //Object "陈学辉" 18

 

 

apply与call基本类似,唯一不同的是函数里参数放在数组里,如果不放在数组里就会报错

 

 apply

1、作用

调用函数并且改变this的指向

2、语法

函数名.apply(thisArg,[arg1,arg2...])

3、参数

   thisArg 函数中this指向的值

[arg1,arg2... ] 从call里的第二个参数开始,都是真正函数里的参数
    

4、返回值

undefined

 

注意:thisArg 的值为null或者undefined的时候,this是指向window

 

function fn(name,age){
    console.log(this,name,age);
}
            
            
fn.apply({a:10,b:20},['kaivon',18]);    //Object "kaivon" 18

/* fn.apply(1,['kaivon']); //如果对应的参数没写的话,那就是undefined fn.apply(1,'kaivon',18); //函数里的参数如果不放在数组中,就会报错 */

 

 

 

 

 

 

 

 

 

posted @ 2017-10-15 15:44  shengnan_2017  阅读(1492)  评论(2编辑  收藏  举报