函数中this的指向

前言: 上下文就是代码的运行环境

1. 普通函数(function)

  • 普通方法调用,this指的就是方法的调用者
var user = {
    print:function(){
        console.log(this);//user 普通函数,谁调用这个函数,this指的就是谁
    }
}
user.print();
  • 普通方法没有调用者,this指向上下文(默认上下文为window)  
function show(){
    console.log(this);//window对象
}
show();
  • 普通方法出现在new对象中,并在对象内使用方法时,this指向上下文(实例对象)
var Stu = function(name){
    this.name = name;
    this.fun =function(){
        console.log(this);//
    }
}
let s = new Stu("stu1"); // 创建对象 会改变对象构造器内部的上下文环境
s.fun();

2、箭头函数(函数名()=>{})

  • 箭头函数在正常环境下使用时,this 恒指向于上下文 (默认值为window)
var user = {
    fun:()=>{
        console.log(this);//window,箭头函数除了在构造函数中,其他地方this恒指向window
    }
}
user.fun();
  • 箭头函数 出现在 new 对象中,并在对象内使用箭头函数的this 恒指向于 上下文 (实例对象)
var Stu = function(name){
    this.name = name;
    this.fun = ()=>{
        console.log(this);//箭头函数在构造函数中,函数中的this指的是实例对象S
    }
}
let s = new Stu("stu1"); // 创建对象 会改变对象构造器内部的上下文环境
s.fun();
  • 当箭头函数 出在new对象中,并且以回调的方式在外部使用时,this 会指向于该函数调用位置的上下文
<div id="app">
    <input type="button" value="设置data中的flag" v-on:click="setFlag()"> 
</div>

<script>
    new Vue({
        el:"#app",
        data:{
            flag:true,
        },
        methods:{
            setFlag:()=>{
                console.log(this);// window对象
            }
        }
    })
</script>
posted @ 2019-07-11 14:06  五两饭  阅读(344)  评论(0编辑  收藏  举报