javascript深入理解之this的指向

139 阅读2分钟

this的理解

1.普通函数调用
2.对象函数(方法)调用(.方式)
3.构造函数调用
4.apply和call调用
5.bind返回值调用
6.箭头函数调用

1.普通函数调用

//定义一个普通函数
var show = function(){
    console.log(this); 
}
//普通函数调用
show();//this => window对象

2.对象函数调用(.方式)

var show = function() {
  console.log(this);
}
var person = {
  show: show
}
person.show(); // this => obj
var showw = person.show;
showw(); //this =>window

再来一个例子

var name = "world";
var person = {
  name:'hello',
  show:function() {
    console.log(this.name);
  }
}
person.show(); //this => obj
var showw = person.show;
showw(); //this =>window

3.构造函数调用

var Person = function(){
  console.log(this);
}
var person = new Person();//this =>//this =>构造实例

4.call和apply调用

call和apply的区别:
相同点:两个方法产生的作用是完全一样的
不同点:方法传递的参数不同
    1.call()方法第一个参数是函数运行的作用域(this),另外的参数以参数列表方式传递
    2.apply()方法第一个参数也是函数运行的作用域(this),另外的参数以数组方式传递
主要的用途:
  1.改变this的指向
  2.方法借用
// 定义一个普通函数
var show = function(){
  console.log(this);
}
//定义一个对象person
var person = {
  name:'person'
}
//定义一个对象pig
var pig = {
  name:'pig'
}
show.call(person); //this =>person
show.apply(pig); //this =>pig

5.bind返回值调用

bind()方法作用跟call()、apply()是一致的,但是bind()方法会返回一个函数

var show = function() {
  console.log(this);
}

var person = {
  name:'person'
}
var newFn = show.bind(person);
newFn(); //this => 打印obj对象

6.箭头函数调用

箭头函数没有自己的this,它的this是继承而来,默认指向在定义它时所处的对象(宿主对象)


var person = {
  name: 'hello',
  say: function(){
    console.log(this); // this => 打印person对象
    var _this = this; // 
    var show = ()=>{
      console.log(_this); // this => 打印person对象
      console.log(this); // this => 打印person对象
    } 
    show();
  },
  listen: () =>{
    console.log(this); // this => 打印window对象
    var _this = this;
    var show = () => {
      console.log(_this); // this => 打印window对象
      console.log(this); // this => 打印window对象
    }
    show();
  }
}
person.say(); 
person.listen();