javascript中this指向问题总结

文章目的是总结下这个事情,如果没有考虑周全,遗漏某一条,请过路的留言写,我在补上。

  1. 在自制行函数中,this --> window
    let obj = {
        name: 'fung',
        getName: ~function(params) {
            // this-->window
           console.log(this); //window
        }() 
    };
  1. 给元素的某个事件绑定方法,当事件触发执行,对应方法的时候,方法中的this一般是指当前操作的元素本身。
let box = document.getElementById('box');
box.onclick = function () {
    // this -- > box
    console.log('box', this); //box对象
}
  1. 当方法执行时,看方法的前面有没有点,如果有点,点前面是谁,this就是指向谁;如果没有点一般都是指向window
var objTest = {
    name: 'fung',
    getName: function () {
        console.log('objTest', this);
    },
    timeout: function(params) {
        setTimeout(function(){
            //this --> window
            console.log('setTimeout', this);
        }, 1000);
    }
};
objTest.getName(); //this --> objTest
let fn = objTest.getName;
fn(); // this --> window
  1. 在构造函数模式中,方法体中出现的this是当前类的一个实例。
function Person(name, age, sex) {
    //this --> person(Person类的实例person)
    this.name = name;
    this.age = age;
    this.sex = sex;
    console.log('Person', this);
}
let person = new Person('fung', 19, 'femail');
  1. 在setTimeout函数中的this一般指向window
objTest.timeout();
  1. call和apply中括号里面的第一个参数是谁this就指向谁。
let oldObjec = {
    name: 'oldObjec',
    age: 1000,
    getName: function() {
        console.log('oldObjec getName', this.name);
    }
};
let newObjec = {
    name: 'newObjec',
    age: 00,
    getAge: function () {
        console.log('newObjec getAge', this.age);
    }
};
let name = 'window';
oldObjec.getName.call(newObjec); //输出newObjec,说明this指向的是newObjec
newObjec.getAge.call(oldObjec);//输出1000, 说明this指向的是oldObject
  1. 箭头函数中的this,就是定义是所在的对象,而不是使用时所在的对象
var age = 111;
function getName () {
setTimeout(() => {
        console.log('arrowObjec getName', this.age);
    }, 1000);
}
getName.call({age: 2000});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值