JS的绑定对象this

this的含义

this表示的是绑定的对象,通常在函数中使用。
不同的代码形式下,绑定的对象代表不同的东西。
下面看一下常见的几种代码形式:

一、独立的函数

function foo() {
    console.log(this); // this就是window对象
    console.log(this.innerWidth); // 打印客户端窗口宽度
}
foo();

二、对象的方法

var obj = {
    x: 10,
    y: 20,
    point: function() {
        console.log(this); // this是方法所属的obj对象本身
        console.log(this.x, this.y); // 打印出obj对象的属性
    }
}
obj.point();

三、事件处理程序

document.addEventListener('click', function() {
    console.log(this); // this是触发事件的那个对象
    this.body.innerHTML += '被点击了!';
})

四、构造函数

function Foo() {
    console.log(this); // this是浏览器自动帮我们新创建的空白对象
    this.x = 1;
    this.y = 2;
}
// new Foo(); // Foo{}
var f = new Foo(); 
console.log(f);
原文地址:https://www.cnblogs.com/buildnewhomeland/p/12781048.html