看了很多文章,说得都不是很简单,开始:
关键字"this"指向了当前代码运行时的对象
this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象
this永远指向的是最后调用它的对象,也就是看它执行的时候是谁调用的
普通定义一个function,定义到了window上去了,所以function this指向的是window这个对象
function a(){
varuser ="追梦子";
console.log(this.user);//undefinedconsole.log(this);//Window}
a();
function a(){
varuser = "追梦子";
console.log(this.user); //undefined
console.log(this); //Window
}
window.a();
// 'use strict'
this.ttt='ttt'
var a = '11'
const obj = {
a:"方法外",
b:function(){
this.a='方法内'
return this.a
},
c:function(){
return this
},
d:() => {
return this
}
}
let c = obj.c
let f = function(){
this.xxx= "xxx"
return this
}
function bbb(){
return this
}
function ccc(){
const d = () => {
return this
}
return d()
}
const ccc02= ()=>{
const d = () => {
return this
}
return d()
}
function ccc03(){
function d() {
return this
}
return d()
}
//function a(){}
//var b = 'b'
//相当于 window.a window.b
//每个js文件就有一个对象,他的this就指向这个对象
//所以这里其实一共有三个对象,一个是global,一个是js文件的this,一个是代码定义的obj对象
//obj.c是一个方法,方法赋给了c,c是global的一个属性,所以好似global调用了function
//所以function,指向的是global
console.log(c())
//同理f也一样,
console.log(f())
//同理bbb也一样
console.log(bbb())
//这里的c是对象obj调用的,所以this指向obj
console.log(obj.c())
let e = ()=>{
return this
}
//箭头函数指向的是上下文对象,所以这里是函数执行上下文对象,也就是当前上下文
console.log(e())
let d = obj.d
//同理也是
console.log(d())
//尖头函数声明时就定义了this指向,和谁调用它没关系,所以也同理
console.log(obj.d())
//这里的this,指的就是上下文对象的this
console.log(this)
//d是尖头函数,它的this指的是函数执行上下文的this,也就是func ccc()的this
//而func ccc()的this指向的是global
console.log(ccc())
//d是尖头函数,它的this指的是函数执行上下文的this,也就是func ccc()的this
// ccc()也是尖头函数,它的this指向的是他自己上下文的this
console.log(ccc02())
//d是普通函数,它的this,没有人调他,相当于global在调他,所以他的this指global
console.log(ccc03())
// 普通函数this指向
// (1)总是代表着它的直接调用者,如obj.fn,fn里的最外层this就是指向obj
// (2)默认情况下,没有直接调用者,this指向window,因为相当于赋值给力window对象
// (3)严格模式下(设置了'use strict'),this为undefined
// (4)当使用call,apply,bind(ES5新增)绑定的,this指向绑定对象
// ES6箭头函数中this
// (1)默认指向定义它时,所处上下文的对象的this指向。即ES6箭头函数里this的指向就是
// 上下文里对象this指向,偶尔没有上下文对象,this就指向window
// (2)即使是call,apply,bind等方法也不能改变箭头函数this的指向
//上下文有三种
//全局执行上下文
//函数执行上下文
//Eval 函数执行上下文
context(上下文)
任何方法,谁调用了它,则就是它的context。
这个和this的描述是一致的:
this最终指向的是调用它的对象
上下文就是this的指向,this的指向是一个对象,所以上下文就是一个对象