this指向

57 阅读1分钟

this指向有以下几种:

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

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

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

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

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

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

4. 构造函数中的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('汉兰达');

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

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

6. 箭头函数没有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();