this的三个要点

1.this的指向是什么

指向对象

2.this可以书写在哪里

可以写在全局,也可以写在函数里

三种写在函数里的方式:

2.1  this可变

function f() {
        this.name = "sun";
    }

2.2  this可变

var o = {
        name: "sun",
        print: function () {
            console.log(this.name);
        }
    };
o.print();// sun
var f = o.print;//调用
f();//undefined;window.f(),现在是window调用的f()函数

2.3  this不可变

var ele = document.getElementById("id");
    ele.addEventListener("click",function () {
        console.log(this);//永远指向ele
    })

3.this指向对象的原则

3.1 运行时决定

3.2 运行在全局时,永远指向window;

  运行在函数时,函数是谁调用的就是指向谁;

原文地址:https://www.cnblogs.com/sunxirui00/p/7551419.html