最重要的就是判断函数是什么时候执行的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
//箭头函数中的this是在定义函数的时候绑定,而不是在执行函数的时候绑定。意识是箭头函数定义的时候就已经确定了this的
//指向了以后就不变了
// var a = 11;
// var obj = {
// a: 22,
// say: function () {
// console.log(this);
// console.log(this.a)
// }
// }
// obj.say(); //谁调用就指向谁
// var b = 11;
// var obj = {
// b: 22,
// // say: () => {
// // console.log(this);
// // console.log(this.b);
// // }
// haha: function () {
// console.log(this.b); //又指向了自己 对象的格式就是键值对
// }
// }
// obj.haha(); //输出的值为11.
var c = 11
function test1() {
this.c = 22; //如果是通过new对象的方式,这个c就是对象的c和外面的c没有关系了
//console.log(this);
let d = () => {
console.log(c);
//console.log(this);
//console.log(this.c + 'haha');
};
d();
return 'hahahahaha'
}
var x = new test1(); //输出11,我这里其实new的只是构造方法,里面的this又指向了windows,输出11
console.log(x); //它也不接返回值
// x.d();
// var x = test1(); //输出22
// console.log(x);
</script>
</head>
<body>
</body>
</html>
默认指向this和window指向的是同一个地址。
函数执行this指向才有意义。
执行一个函数,就会有一个this执行(不管这个函数是不是嵌套在里面)
this指向可能相同,也可能不同。
只要看它是不是独立调用来确定this的指向。
判断this指向主要是判断函数是在哪里执行的。
父函数是有能力绝对子函数的this指向的。
当函数作为参数的时候,我们就可以把函数定义为回调函数。
new返回的是实例之后的对象。
实例对象就是构造函数返回的this
new一个函数,生成一个实例化对象,这种函数就叫做构造函数。
只要是对象就可以通过对象调用,call调用,new调用。
箭头函数是不允许作为构造函数使用的。
1:11:39
大佬:https://www.bilibili.com/video/BV1NT4y1j7xH?p=2