// 1、全局环境下的this: window
console.log(this);
// 2、事件处理函数中的this: 触发这个事件的元素
box.onclick = function(){
console.log(this);
}
// 3、定时器中的this: window
setTimeout(function () {
console.log(this);
}, 1000);
// 4、函数直接执行中的this(严格模式下是undefined)
// 严格模式:在函数里面第一行加上:"use strict";。则当前这个函数以严格模式解析
function fn() {
"use strict";
console.log(this);
var a = 5;
console.log(a);
}
fn();
// 5、call apply。作用:调用函数,可以修改函数中的this指向
// 6、对象方法内部调用
var obj = {
name: 'obj',
fn: function () {
console.log(this);
}
};
obj.fn(); // this指向obj
var v = obj.fn;
v(); // this指向window
// 7、构造函数中的this: new实例化的时候创建出来的哪个对象
// 8、原型链函数中的this:关键看原型链中的函数被谁调用,一般情况下指向这个对象
function Fn() {
console.log(this);
}
Fn.prototype.show = function () {
console.log(this);
}
var f = new Fn();
f.show();
// 9、所有的回调函数里面的this是 window