# 【JS原生】this指向基础-笔记-(unfinished)

# 未完成:(五)箭头函数的this指向/改变this指向

# 提示: 基本情况有五种!!

(如有错误,敬请指正)

拓展:

在浏览器环境中,全局对象指的是 window 对象

在Node.js环境中,全局对象为 Global 对象


# (一)普通函数---this指向全局(window)对象

# (一)例一

function foo(){
    console.log(this)
}
foo(); //this指向全局对象
1
2
3
4

# (二)对象方法中的this---指向“调用”该方法的对象

# (二)例一

const student = {
    name:"zhangsan",
    sayName:function(){
        console.log(this.name);
    }
};
student.sayName(); //zhangsan
1
2
3
4
5
6
7

img

# (二)例二

const student = {
    name:"zhangsan",
    sayName:function(){
        console.log(this.name);
    }
};
const person = {name:"lisi"}; //创建新的对象 person
person.sayName = student.sayName; // 将student对象的方法属性赋值给person对象

person.sayName(); //lisi
1
2
3
4
5
6
7
8
9
10

img


# (三)事件里面的this---指向绑定该事件的”元素“

# (三)例一

//原生JS创建父子节点元素
var a = document.createElement("div");
var b = document.createElement("div");
a.setAttribute("id","father");
a.setAttribute("style","width:100px;height:100px;background-color:red;");
b.setAttribute("id","son");
b.setAttribute("style","width:50px;height:50px;background-color:blue;");
a.appendChild(b);
document.body.appendChild(a);
	
//父元素绑定点击事件
var xx = document.getElementById("father");
xx.onclick = function(){
	console.log(this);
}
//先点击红色 控制台 显示 id="father"元素
//再点击蓝色 控制台 显示 id="son"元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

img

拓展:event.target的区别-【JS学习】杂项:event.target 与 this 区别 - 不想笑的山姆的文章 - 知乎 (opens new window)


# (四)构造函数中的this---指向 "调用new时创建的 ' 实例 ' 对象 "

# (四)例一

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

//原型同样指向 "调用new时创建的 ' 实例 ' 对象 "
person.prototype.sayName = function(){
    console.log(this);
}

var a = new person();
var b = new person();
1
2
3
4
5
6
7
8
9
10
11

img

# (五)箭头函数的this指向

  • 根据执行上下文判断

(四)例一

(四)例一