this的指向大概有下面七种情况
1.在普通函数和全局环境下
this指向window
function demo(){
this.x = 10
console.log(this)// window
}
demo()
console.log(this.x) //10
2.构造函数
构造函数就是函数new出来的对象,所以this指向该对象
function Foo(){
this.x = 10;
console.log(this); //Foo {x:10}
}
var foo = new Foo();
console.log(foo.x); //10
3.对象方法
this指向对象,但是有个小点需要注意:若在对象方法中定义函数,那么该函数this指向的是window
var obj = {
x: 10,
boo: function(){
console.log(this) //obj
console.log(this.x)//10
},
foo: function () {
function f(){
console.log(this); //Window
console.log(this.x); //undefined
}
f();
}
}
obj.foo();
4.prototype属性中
function Foo(){
this.x = 10;
}
Foo.prototype.getX = function () {
console.log(this); //Foo {x: 10, getX: function}
console.log(this.x); //10
}
var foo = new Foo();
foo.getX();
在 Foo.prototype.getX 函数中,this 指向的 foo 对象。不仅仅如此,即便是在整个原型链中,this 代表的也是当前对象的值。
5.call、apply或者 bind 调用
当一个函数被 call、apply 或者 bind 调用时,this 的值就取传入的对象的值。
var obj = {
x: 10
}
function foo(){
console.log(this); //{x: 10}
console.log(this.x); //10
}
foo.call(obj);
foo.apply(obj);
foo.bind(obj)();
6.DOM event
在一个 HTML DOM 事件处理程序里,this 始终指向这个处理程序所绑定的 HTML DOM 节点:
function Listener(){
document.getElementById('foo').addEventListener('click', this.handleClick); //这里的 this 指向 Listener 这个对象。不是强调的是这里的 this
}
Listener.prototype.handleClick = function (event) {
console.log(this); //<div id="foo"></div>
}
var listener = new Listener();
document.getElementById('foo').click();
7.箭头函数中的 this
var obj = {
x: 10,
foo: function() {
var fn = () => {
return () => {
return () => {
console.log(this); //Object {x: 10}
console.log(this.x); //10
}
}
}
fn()()();
}
}
obj.foo();