this指向

this出现在全局函数中,永远指向window

var Car = function() {
    console.log(this); // window
    console.log(this.Car==window.Car,Car==window.Car); // true true
}
Car();

 函数中使用es5的严格模式‘use strict’,this为undefined

 var Car = function() {
    'use strict'
    console.log(this); // undefined
}
Car();

  当某个函数为对象的一个属性时,在这个函数内部this指向这个对象

var car = {
    name:'张三',
    run() {
        console.log(this); // {name: "张三", run: ƒ}
    }

  构造函数中的this,指向构造函数新创建的对象

var Car = function(name) {
    this.name = name;
    console.log(this); // Car {name: "张三"}
                       // Car {name: "李四"}
}
var myCar_1 = new Car('张三');
var myCar_2 = new Car('李四'); 

 绑定事件中的this,指向被点击的这个元素

 var btn = document.querySelector('button');
btn.onclick = function() {
    console.log(this); // <button>this</button>
}

箭头函数没有this,它的this是继承而来,默认指向在定义它时所处的对象 

const obj = {
    Car() {
        setTimeout(function() {
            setTimeout(function() {
                console.log(this); // window
            })
            setTimeout(()=>{
                console.log(this); // window
            })
        })
        setTimeout(() => {
            setTimeout(function() {
                console.log(this); // window
            })
            setTimeout(()=>{
                console.log(this); // obj
            })
        })
    }
}
obj.Car()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值