this用于访问当前方法调用时所属的对象,函数的this和定义无关和调用有关

    1、 直接调用如果是普通函数普通模式指向windows,对于严格模式指向undefined

    1. function show() {
    2. console.log("this 指向"+this)
    3. }
    4. show();

    image.png
    2、挂在对象上,然后执行方法——this为对象

    1. document.onclick = function () {
    2. console.log("this 指的是"+this)
    3. }

    image.png
    3、定时器———this为window

    1. setTimeout(function(){
    2. console.log("this 指的是"+this)
    3. },100)

    image.png
    4、构造函数new ———-当前构造函数的对象

    1. function Show() {
    2. console.log("this指得是"+this )
    3. }
    4. var show = new Show();

    5、工具函数
    this根据第一个参数决定

    1. function Show() {
    2. console.log("this指得是"+this )
    3. }
    4. Show.call(this)
    5. Show.call(88)

    image.png
    其次foreach的第二个参数不写的话,this指向window

    1. let arr = [1, 2, 3, 4]
    2. arr.forEach(function(item){
    3. console.log("this指的是" + this)
    4. });

    image.png
    如果第二个参数写进去的话同call apply的用法

    1. let arr = [1, 2, 3, 4]
    2. arr.forEach(function(item) {
    3. console.log("this指的是" + this)
    4. },"name");

    image.png
    https://www.bilibili.com/video/BV1MZ4y1H7e7