> 文档中心 > 【function this的指向性问题】

【function this的指向性问题】

目录

一,传统函数中的this指向

1,在全局中定义的函数,this指向window

2,对象方法中的this指向这个对象

3、构造函数创建对象的方法中的this指向new出来的实例化对象

4、定时器中匿名方法的this—指向window对象

 二,箭头函数中的this指向


一,传统函数中的this指向

原则:方法由谁调用,this就指向谁

1,在全局中定义的函数,this指向window

   var name = "mickey "; //全局变量name相当于是window. name function person() {     //this.name= "tom";这里改了之后,上面定义的全局变量name随之改变     console.log(this); //window     console.log(this.name); //mickey } //普通函数调用 person(); //相当于window. person()

2,对象方法中的this指向这个对象

      //当作某个对象的方法 var name = "tom"; var person = {     name: "tom",     showName: function() {  console.log(this.name);     } } person.showName() //tom  this指向person

3、构造函数创建对象的方法中的this指向new出来的实例化对象

  var name = "mickey"; function Person(name) {     this.name = name;     this.showName = function() {  console.log(this.name); //"tom"  console.log(this);//Person     } } var p = new Person("tom"); p.showName();

4、定时器中匿名方法的this—指向window对象

 var name = "mickey"; function Person(name) {     this.name = name;     this.showName = function() {  // console.log(this.name);  setTimeout(function() {      console.log(this.name); //mikey      console.log(this); //window  }, 1000)     } } var p = new Person("tom"); p.showName(); //"tom"

 二,箭头函数中的this指向

        箭头函数体内的this对象就是定义时所在的对象,而不是使用时所在的对象。

        简单而言,箭头函数使用时,不绑定this对象,箭头函数没有自己的this,它的this是继承而来的,默认指向在定义箭头函数时所处的对象。

     

function foo() {  return () => {    return () => {      return () => { console.log('id:', this.id);      };    };  };}var f = foo.call({id: 1}); // 设置foo的id为1var t1 = f.call({id: 2})()();     // id: 1var t2 = f().call({id: 3})();     // id: 1var t3 = f()().call({id: 4});     // id: 1//上面代码之中,只有一个this,就是函数foo的this。所以t1、t2、t3都输出同样的结果。

因为所有的内层函数都是箭头函数,都没有自己的this,它们的this其实都是最外层foo函数的this。所以箭头函数的this指向是创建它所在的对象,不会改变。