美文网首页
this的指向和改变this的指向

this的指向和改变this的指向

作者: 北〤极星_ | 来源:发表于2020-06-12 16:20 被阅读0次

一、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("小亮"); 

相关文章

网友评论

      本文标题:this的指向和改变this的指向

      本文链接:https://www.haomeiwen.com/subject/alggtktx.html