JS中的this关键字

this关键字

JS中的this代表的是当前行为执行的主体:JS中的context代表的是当前行为执行的环境(区域)

this是谁和函数在哪定义的和在哪执行的都没有任何的关系,这和它的执行主体有关。

如何区分this

  • 函数执行,首先看函数名前面是否有“.”,有的话,“.”前面是谁this就是谁, 没有的话this就是window
function fn(){
    console.log(this);
}
var obj = {fn :fn};
fn(); // window
obj.fn(); // obj
function sum(){
    fn():
}
sum(); // window

var oo = {
    sum: function(){
        fn();
    }
}
oo.sum(); // window
  • 自执行函数中的this永远是window
  • 给元素的某一个事件绑定方法,当事件触发的时候,执行对应的方法,方法中的this是当前的元素
function fn(){
    console.log(fn)
}
document.getElementById('div1').onclick = fn; // #div1
document.getElementById('div2').onclick = function(){
    // #div2
    fn();  // window
}
  • 使用 new, 在构造函数模式中,类中(函数体中),this.xxx = xxx是当前类的实例
function CreateJsPerson(name, age){
    this.name = name;
    this.age = age;
    this.writeJS = function(){
        console.log("my name is " + this.name + ", i can                write js ~~")
    }
    console.log(this)
}

var p1 = new CreateJsPerson("lemon1", 21)
// Object { name: "lemon1", age: 21, writeJS: writeJS() }
posted @ 2020-09-09 17:52  lemon-Xu  阅读(302)  评论(0编辑  收藏  举报