// 这里是全局中的 this 是指向 window 的
console.log(this);
var a = 10;
// 可以直接使用 window.a 输出的结果为10
console.log(this.a);
function box1() {
// this 是指向 window 的
console.log(this);
function box2() {
// this 是指向 window 的
console.log(this);
function box3() {
// this 是指向 window 的
console.log(this);
}
// 这里相当于是window去调用的
box3();
}
// 这里相当于是window去调用的
box2();
}
// 这里相当于是window去调用的
box1();
// 在点击事件中, this 指向的是当前触发事件的元素对象
document.body.onclick = function() {
// 指向的是 body 对象
console.log(this);
}
document.querySelector('.box1').onclick = function(e) {
// this 执行结果,为 div.box1 对象
console.log(this);
// 阻止消息冒泡,不然上面的body 会输出
e.stopImmediatePropagation();
}
$('div').click(function() {
// 会输出当前被点击的 div 对象
console.log(this);
})
// 在构造函数中,this 表示的是正在初始化的对象本身
function Base(name) {
// this 指的是当前在创建的对象
console.log(this);
this.name = name;
console.log(this);
}
var ba = new Base('小明');
var obj = {
name: '小强',
age: 20,
run: function() {
// 这里 this 是 window (主要是看谁来调用的这个方法)
console.log(this);
}
}
var fun = obj.run;
fun();