zoukankan      html  css  js  c++  java
  • JS中this的指向性问题

    一、this用于访问当前方法所属的对象,谁调用的方法,方法就属于谁

    // 普通函数
    let obj = {
        a : 12,
        fn() {
            console.log(this == obj); // true
        }
    }
    
    document.onclick = function () {
        console.log(this); // document
    };
    
    obj.fn();
    

    二、函数的this跟定义无关,跟调用有关

    function show() {
        console.log(this);
    }
    

    1. 直接调用 -> window || undefined

    show();
    

    2. 挂在对象上,然后执行方法

    let array = [1, 2, 3];
    array.fn = show;
    array.fn(); // [1,2,3,fn]
    

    3. window

    setTimeout(show, 100);
    

    4.构造函数 -> 当前构造的实例

    new show(); //show{}
    

    5. 工具函数

    show.call(12); // 12
    

    6. forEach里面的回调函数的this

    let arr1 = [1, 2, 3];
    // reason
    arr1.forEach = function (cb) {
        for (let i = 0; i < this.length; i++) {
            cb(this[i]);  // 这里的回调函数是无指向的,cb是windows调用的,因此下面的this指向不稳定,这里的this和下面的this不是同一个东西
        }
    };
    arr1.forEach(item => {
        console.log(this);  // window || undefined
    })
    

    7. 解决forEach回调函数的this的指向问题

    let arr2 = [1, 2, 3];
    // reason
    arr2.forEach = function (cb,thisArg) {
        for (let i = 0; i < this.length; i++) {
            cb.call(thisArg,this[i]);  // 这里的回调函数是无指向的,因此下面的this指向不稳定
        }
    };
    arr2.forEach(item => {
        console.log(this);  // window || undefined
    },document)
    

    8. 箭头函数中的this

    // 箭头函数中的this指向被定义时的对象,与调用者无关
    var jtFun = () => {
        console.log(this);
    }
    let jt = {
        fnc: jtFun
    }
    
    jt.fnc(); // window
    
  • 相关阅读:
    ansible命令应用示例
    ansible运维自动化工具
    grep 命令使用指南
    Nginx httpS server配置
    find 使用指南
    fastcgi_param 详解
    nginx虚拟主机的配置
    shell中字体变色
    nginx.conf 配置文件详解
    php-fpm.conf 配置文件详解
  • 原文地址:https://www.cnblogs.com/eden-libinglin/p/13935923.html
Copyright © 2011-2022 走看看