es5中的this,es6中箭头函数中的this

一.判断this的绑定对象

1.对于构造函数,new一个新对象,this绑定到新建立的对象上es6

function Fun(){
    this.user ='fff';
}
var fun1 = new Fun();
console.log(fun1.user);//'fff'

2.由call或者apply调用,this绑定到指定的对象上app

function Fun(){
    console.log(this.user);
}
var obj1 ={
    user:'obj1',
    fun:Fun
}
var obj2 ={
    user:'obj2',
    fun:Fun
}
obj1.fun.call(obj2);//obj2

3.函数是否在某个上下文环境中调用,若是是的话,this指向的是那个上下文环境异步

(1).若是一个函数中有this,并被上一级对象所调用,那么他指向上级对象
    function Fun(){
        console.log(this.user);
    }
    var obj1 ={
        user:'obj1',
        fun:Fun
    }
    obj1.fun();//obj1
(2).若是函数中有多个对象,this仍是指向他的上一级对象
    function Fun(){
        console.log(this.user);
    }
    var obj1 ={
        user:'obj1',
        foo:{fun:Fun}
    }
    obj1.foo.fun();//undefined

4.若是以上都不是的话就使用的是默认绑定,在严格模式下,绑定到undefined,在非严格模式下,绑定到全局对象函数

5.当new一个对象时遇到return总结:若是return的是一个函数或者是对象,this指向的就是return出的函数或者对象;反之,this指向的是调用他的实例this

eg1.
function Fun(user){
    this.user =user;
    return {};//或者是function(){}
}
var a = new Fun();
console.log(a);//{}
//这个时候的this是指向return出的空对象的

eg2.
function Fun(user){
    this.user =user;
    return 1;//或者是undefined
}
var a = new Fun();
console.log(a);//Fun {user: undefined}
//this指向新建立的对象

二.es6箭头函数中的this

1.箭头函数中thisspa

(1)箭头函数中的this指向词法做用域,即外层调用者code

不使用箭头函数:
eg:
var a = {
  name: function() {
    console.log(this);
  }
}
a.name();//此时的this是指向对象a


使用箭头函数:
var a = {
  name: () => {
    console.log(this);
  }
}
a.name();//此时的this指向全局window

(2).箭头函数中call或者apply并不能修改this的指向对象

eg:
var a = {
  name: () => {
    console.log(this);
  }
}
a.name.call({ b: '11' });//此时this仍是指向window

(3).多层嵌套,箭头函数中的this指向最最外层做用域
eg1:ip

var a = {
  b: {
    c: {
      d: () => {
        console.log(this);//此时的this是指向window的
      }
    }
  }
}

eg2:
clipboard.png作用域

(4).与异步函数的例子
eg1:

window.name = "window";
var a = () => {
  console.log('1', this.name, this); //输出window,this指向window
  this.name = "yyy";
  console.log('2', this.name, this); //输出yyy,this仍是指向window
  setTimeout(() => {
        console.log(this.name, this); //输出yyy,说明this是指向window
  }, 1000)
}
a();
详细说明:
a是一个普通函数, 当执行到 console.log('1', this.name, this);时, 在function中并无定义name属性, 因而根据词法做用域向他的上一级去找是否有name属性, 在window中找到, 输出window.name的值;接着把全局属性name的值改成 'yyy';最后, 在一秒钟后执行异步函数setTimeout输出yyy, 此时因为箭头函数的做用, 异步函数中的this仍是指向window

eg2:

var b = {
  c: function() {
setTimeout(() => {
  console.log(this);//此时的this指向函数c
}, 1000);
  }
}
b.c();

输出结果:
clipboard.png

总结:箭头函数中的this是在函数定义的时候就已经肯定,并非指向调用函数时的上下文

箭头函数中, this指向的固定化,并非由于箭头函数内部有绑定this的机制,实际缘由是箭头函数根本没有本身的this,致使内部的this就是外层代码块的this。正是由于它没有this,因此也就不能用做构造函数。
相关文章
相关标签/搜索