1、构造函数中this的指向————对象
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function CreatPerson(){
this.name = "李伟";
console.log(this);
console.log(this.name);
}
//构造函数中的this指向了创建出的对象
//为什么this指向的是对象?
//new关键字会在内存中开辟一块空间,这个空间在设置好值后会把地址交给per1这个变量,所以per1就是创建出来的对象的“代言人”,而空间存在的“this”,也就指向了per1;
var per1 = new CreatPerson();
</script>
</body>
</html>
2、this在事件函数中的指向————触发这个事件的标签
<body>
<button class="btn1">button1</button>
<button class="btn2">button2</button>
<button class="btn3">button3</button>
</body>
<script type="text/javascript">
// 获取到第一个按钮
// var btn1 = document.getElementsByClassName('btn1')[0];
// console.log(btn1);
// btn1.onclick = function () {
// console.log(this);
// }
// 当this出现在事件函数中时,this就指向触发这个事件的标签
for (var i = 1; i < 4; i++) {
var btn = document.getElementsByClassName('btn'+i)[0];
btn.onclick = function () {
console.log(this);
}
}
</script>
3、this在定时器中的指向————window
<script type="text/javascript">
var a = 23;
function Demo() {
this.a = 12;
var self = this;
setInterval(this.show, 1000);
}
Demo.prototype.show = function() {
alert(this.a);
};
var demo = new Demo();
demo.show();
setInterval( function () {
console.log(this);
},1000);
setTimeout(function() {
console.log(this);
}, 1000)
// 结论:如果由定时器调用执行了某个函数,函数中有this,则这个this
</script>
4、this在普通函数中的指向————-谁调用并执行就指向谁
<script type="text/javascript">
// 定义一个普通函数
function demoFun1() {
alert(this);
}
// 调用普通函数时,函数中的this指向的是window
// demoFun1();
// 以上这种调用方式的本质就是下边这种写法:
// window.demoFun1();
// 定义一个全局变量其实就是给window对象添加了一个属性
var name = "王丽媛";
function obj() {
var name = "李威";
console.log(this); // window
console.log(this.name); // 如果window对象有name,则打印name值,否则打印为空
}
// obj();
var obj1 = {
name: "刘孟瑾",
sayName: function() {
console.log(this.name);
}
}
obj1.sayName(); // 调用者是obj1,所以打印的是obj1的name
var tempFun = obj1.sayName;
tempFun(); // 调用者是window,所以打印的是window的name
总结:this在普通函数中的指向,谁调用执行了这个函数,那么函数中的this就指向谁
// 练习
var obj2 = {
name: "张立文",
obj3: {
sayName: function() {
console.log(this.name)
}
}
}
obj2.obj3.sayName();
</script>
5、通过call/apply来修改this的指向
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
// call是function数据类型提供的一种方法:修改被调函数内部指针的指向。
// var name = "刘孟瑾";
// var liWei = {
// name: "李威"
// };
// var wangLiYuan = {
// name: "王丽媛"
// };
// function getName (age) {
// alert(age);
// };
// getName(); // 普通函数调用,this指向的是window
// getName.call(wangLiYuan);
// getName.apply(wangLiYuan);
// getName.apply(null, [12]);
// call和apply的作用和用法完全一样。只是在传递参数时,call把所需要的函数参数依次列举出来;而apply需要把函数参数包装进一个数组中传递;
window.onload = function () {
var btn = document.getElementById('btn');
btn.onclick = function () {
console.log(this);
function inner () {
console.log(this);
}
inner.call(this);
}
}
</script>
</head>
<body>
<button id="btn">button</button>
</body>
</html>