普通函数中的this和箭头函数中的this

普通函数与箭头函数的this指向有哪些不同?
普通函数:
浏览器在解析函数的时候,会默认传递一个隐含的参数给函数,这个参数就是this。this指向的是一个对象,这个对象称为函数的执行上下文。

函数中,this和arguments这两个函数的属性,只有在函数被调用的时候,也就是函数的执行上下文创建后,才会确定它们分别是指向谁。
https://www.jianshu.com/p/d647aa6d1ae6
根据函数调用方式的不同,this的指向也不一样。
(1)以函数的形式调用,在严格模式下,this指向的是undefined,但是在非严格模式下会自动指向全局对象window;
(2)以方法的形式调用,不管是在严格模式还是非严格模式,this指向的都是调用这个方法的对象。

一般函数的调用:
function sum(x,y){
            console.log(this,x+y)
        }
sum(2,3)
//严格模式下
function fn(){
    'use strict'
    console.log(this)
  }
fn()//undefined

'use strict'
var obj = {
  a: 10,
  fn: function () {
    return this.a;
  }
}
console.log(obj.fn())//10

上面这个例子,打印出的this是window。其实在执行中也等同于下面的写法:

 function sum(x,y){
            console.log(this,x+y)
        }
sum.call(window,2,3)
//call(obj,...args):call()在sum()调用的时候,sum()的this指向了obj。
对象里面函数的调用:
 const person = {
           name:'杨洋',
           say:function(age){
               console.log('我是'+this.name+','+age+'岁')
           }
       }
    //person.say(18)
    //等同于下面的写法
    person.say.call(person,18)//call()把第一个参数给到了say()中的this

var obj1 = {
    num : 20,
    fn : function(n){
        console.log(this.num+n);
    }
};
var obj2 = {
    num : 15,
    fn : function(n){
        console.log(this.num-n);
    }
};
obj1.fn.call(obj2,10);//25

            var name = '螺蛳湾'
            function fn(){
                console.log(this.name)
            }
            //以函数形式调用
            fn() //螺狮湾

            const obj = {
                name:'国米',
                price:188,
                say:fn
            }
            //以对象方式调用
            obj.say()//国米
          function Func(){
              this.age = 19;
                this.func=function(){
                console.log(this)  //Func的实例对象
                    function inner(){
                        console.log(this) //window
                    }
                    inner()
                }
            }
            var f = new Func()
            f.func()

new构造函数中的this、原型对象上的this:

function Fn(name){
     this.name = name
     console.log(this)//Fn {name: "哈哈"}
}
const fn = new Fn('哈哈')//new 构造函数的时候,this指向的是构造函数的实例对象

//举个其它例子
function Person(name, age) {
  // 这里的this指向了谁?
  this.name = name;
  this.age = age;
  console.log(this)//Person {name: "Nick", age: 20}
}

Person.prototype.getName = function() {
  // 这里的this又指向了谁?
  console.log(this)//Person {name: "Nick", age: 20}
  return this.name;
}

// 上面的2个this,是同一个吗?
var p1 = new Person('Nick', 20);
p1.getName();

我们知道,this的指向是由函数的调用方式决定的。new操作符调用构造函数,那么this会指向创造的实例对象,所以上面的例子中,this指向的是p1。getName()是由p1调用,所以getName()中的this指向的也是p1。


window.setTimeout()和window.setInterval()默认的是this是window对象。


箭头函数:
箭头函数中的this在定义箭头函数的时候就已确定,指向的是定义时所在的对象。
其它的说法是:箭头函数本身没有this,箭头函数中的this取决于箭头函数外部函数(我认为是作用域可以吗)中this的值。
又有人说:根据MDN文档,箭头函数不会创建自己的this,只会沿着作用域链继承上一层的this。
看下面的例子:

let obj = {
            a:1,
            say:function(){
              return ()=>{
                console.log(this)//obj
          }
     }
}
obj.say()()

根据"箭头函数中的this取决于箭头函数外部函数中this的值",this的值取决于say()中的this的值,而say()中的this指向的是obj,所以箭头函数中输出的this就是obj。
多层嵌套的箭头函数中的this:

let _this = this
          let obj = {
            a:1,
            say:() =>{
              let _this1 = this
              console.log(_this1 === _this)
              return () =>{
                let that = this
                console.log(that === _this)
                return ()=>{
                  console.log(this === that)
                }
              }
            }
          }
          obj.say()()()// true  true  true

从执行结果可以看出,多个箭头函数嵌套,最内部箭头函数的this继承自作用域链上一层的this,上一层又继承自上上一层,直至到顶层的this。
call()、apply()、new构造函数能改变箭头函数中的this指向吗?

        let showName = (name)=>{
          this.name = name
          console.log(this.name)
        }
        let obj = {
          name:'杨洋'
        }
        showName.call(obj)//undefined
        showName.apply(obj)//undefined
        let myName = new showName(obj.name)//showName is not a constructor

从结果来看,很明显,都不能改变箭头函数中的this指向。

//有这样一个需求,点击某元素,500ms后,改变背景颜色
//不使用箭头函数的写法:
let item = document.querySelector('.item') item.addEventListener('click',function(){ setTimeout(function(){ //无法实现效果 this.style.backgroundColor = 'red' },500) }) //由于匿名函数的存在导致了this指向的丢失,在这个匿名函数中this指向了全局, //因此我们需要想一些办法找回正确的this指向。 item.addEventListener('click',function(){ let _this = this setTimeout(function(){ _this.style.backgroundColor = 'red' },500) }) //使用箭头函数的写法: let item = document.querySelector('.item') item.addEventListener('click',function(){ setTimeout(()=>{ //箭头函数中的this始终指向的是函数所属的那个作用域,所以这里的this就是item这个元素 this.style.backgroundColor = 'red' },500) })

你可能感兴趣的:(普通函数中的this和箭头函数中的this)