This

  • this -> 函数内部的一个执行期的上下文指向
  • this 明确指向的时机:执行期
  • 函数的执行条件与环境决定了 this 指向
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function test() {
// this -> sth
// this -> window
// use strict this -> undefined
console.log(this);
}

test()

var obj = {
test: test
}
//谁调用test -> test内部的this -> obj
obj.test()

//一个函数内部是有隐式的this
//当函数执行的时候,决定this -> 谁

function test1() {
console.log(this);
}

// 指示函数test1执行
// 函数内部的this -> 新的对象
// 执行期间返回this

New的过程

  • 在函数内部隐式创建一个对象
  • 将this -> 新对象
  • 将this上挂载的属性,放入新对象
  • 隐式返回this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var t = new test1()
console.log(t)


//函数声明与函数表达式中的this在非严格模式下,自调用,this -> window
function test2(callback) {
callback()
}

test2(function () {
console.log(this); //window
})

var obj = {
test: function (callback) {
// this -> obj
callback()
}
}

obj.test(function () {
console.log(this); // this
})


var obj2 = {
test: function () {
var test1 = function () {
console.log(this); //window
}
test1()
}
}

var obj3 = {
test: function () {
obj.test1 = function () {
console.log(this);
}
obj.test1()
}
}
obj3.test()

var p = new Promise(function (resolve, reject) {
console.log(this); //自调用 -> window
})

var obj4 = {
test: function () {
console.log(this);
}
}

obj4.test() // obj4对象
var a = obj4.test
a() // window
  • function declaration 函数声明
    • function test () {}
    • var a = 1
  • function expression 函数表达式
    • var test = function () {}
  • 函数声明和函数表达式内部的this -> 执行器的环境和调用方式 -> 不稳定的
  • arrow function -> 作用在于稳定程序中的this指向
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
'use strict'
var test3 = () => {
//全局test3 -> this -> window
console.log(this);
}

// 箭头函数 this -> 始终保持与父级作用域的this一致
var obj5 = {
test: () => {
// 父作用域 -> global -> window
console.log(this); // window
}
}

var obj6 = {
test(callback) {
callback()
}
}

// callback父作用域 -> global -> window

obj6.test(() => {
console.log(this);
})