this的指向问题,后续陆续补全中。。。
目录
4)定时器(setTimeout setInterval)函数中的this
1)在全局函数中调用this
function fn() {
console.log(this);
}
fn();
控制台输出:
结论:this指向window
2) 在对象的方法中调用this
var a = {
b: {
name: "lisi",
c: {
name: "wangwu",
say: function() {
console.log(this);
}
}
},
name: "zhangsan"
}
a.b.c.say();
控制台输出:
结论: this指向调用者。 a.b.c.fn() 调用者是c 看函数名前面的是谁。
3)事件处理函数中的this
#box{
width:100px;
height:100px;
background-color:#ccc;
}
<body>
<div id="box">
</div>
</body>
var box = document.getElementById("box");
box.onclick = function(event) {
console.log(this);
}
控制台输出:
结论:this指向事件源。
4)定时器(setTimeout setInterval)函数中的this
setTimeout(function() {
console.log(this);
}, 1000)
控制台输出:
结论: this指向window
5)构造函数中的this
function Person(name) {
this.name = name;
}
var person = new Person("张三")
console.log(person);
控制台输出:
结论: this指向构造函数创建出来的对象。