this的指向和改变this的指向

一、this的指向

普通函数调用

function fn(){

       console.log(this) //this指向window

}

fn()

对象方法的调用

var obj={

    name:"小明",

    fn:function(){

          console.log(this.name)//输出小明  此时的this指向obj

  }

}

obj.fn()

构造函数的调用

function Fn(name,age){

    this.name=name;

    this.age=age

    console.log(this) //此处 this 分别指向 Fn的实例对象

}

var  person=new Fn('小明',18)

二、改变this的指向


1.call() bind 方法改变函数的this

var person={

    name:"小明",

    age:18

}

function fn(name,age){

        console.log(this.name);  //小明  

        console.log(this.age); //18

        console.log(name,age) //小亮 16

        //此时的this指向 person

 } 

fn.call(person,'小亮',16  );

2.apply() 方法和call() 类似只是第二个参数接收一个数组

let obj = {    

fn: function (a) {     

       console.log(this.name)   //小明

       console.log(this.age) //18

       console.log(a)  // 小亮  16

    //此时的this指向person 

  }},

    person = {  

      age: 18,

        name: "小明"  

  };

obj.fn.apply(person, [{    name: "小亮",    age: 16,}])

2. bind()方法改变函数的this

let obj = {   

 name: "小明",    

getName: function () {    

     return this.name

  }}

function getName(name) { 

 console.log(this.getName()) //小明

 console.log(this.name);   //小明

 console.log(name) // 小亮

}

var getNameFn = getName.bind(obj);

getNameFn("小亮"); 

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容