看啥推荐读物
专栏名称: Caesar Liu
创始人
目录
相关文章推荐
今天看啥  ›  专栏  ›  Caesar Liu

this引用分析 - 懒猴子CG20191124技术分享总结

Caesar Liu  · 掘金  ·  · 2019-11-25 15:14
阅读 53

this引用分析 - 懒猴子CG20191124技术分享总结

说明

  • 分享时间:2019/11/24
  • 分享目的:助力后端程序员成为团队中最会写前端的后端
  • 分享内容:
    • 常见的前端安全问题和防范(闭包、防止xss攻击)
    • 常见知识点分析(prototype、setTimeout、this指向、Promise)
    • 一套高可读、高可维护的代码编写规范(BaseController、call、PageController)
  • QQ交流群:877957236

重点内容:this引用分析

判断this指向谁,用以下三句话:

  1. 定义函数时采用非箭头函数,this指向为函数所属对象,如果没有所属对象则默认为Window(示例1至示例6证明)
  2. 定义函数时采用箭头函数,this指向为上下文对象,如果没有上下文对象则默认为Window(示例7至示例8证明)
  3. 除setTimeout, setInterval,在使用'use strict'的情况下,默认为undefined(示例9至示例12证明)

更详细的内容可以参考mozilla文档

示例 & 分析

// 示例1
console.log('示例1', this); // Window,默认为Window

// 示例2
function func2() {
    console.log('示例2', this); // Window,因为func函数所属window
}
func2();

// 示例3
var json = {
    m1: function () {
        console.log('示例3', this); // json,因为m1函数所属json
    }
};
json.m1();

// 示例4
var json = {
    m1: function () {
        console.log('示例4', this); // Window,因为func所属Window
    }
};
var func4 = json.m1;
func4();

// 示例5
var json = {
    prop: {
        name: 'prop',
        obj: {
            m1: function() {
                console.log('示例5', this); // obj,因为m1所属obj
            }
        }
    }
};
json.prop.obj.m1();

// 示例6
var json = {
    m1: function (){
        setTimeout(function() {
            console.log('示例6', this); // Window,因为setTimeout中的function没有所属对象,this默认指向Window
        }, 0)
    }
};
json.m1();

// 示例7
var json = {
    m1: function() {
        var func = () => {
            console.log('示例7', this) // json,m1所属json,即m1中的this指向json,则执行func函数的上下文对象为json
        };
        func();
    }
};
json.m1();

// 示例8
var json = {
    m1: () => {
        var func = () => {
            console.log('示例8', this) // Window,执行m1方法的上下文对象默认为Window,则执行func函数的上下文对象也为Window
        };
        func();
    }
};
json.m1();

// 示例9
function func9() {
    'use strict';
    console.log('示例9', this)
}
func9();

// 示例10
(function() {
    'use strict';
    var json = {
        m1: function() {
            var func = () => {
                console.log('示例10', this) // undefined,func10所属undefined,即m1中的this为undefined,则func中的this也为undefined
            };
            func();
        }
    };
    var func10 = json.m1;
    func10();
})();

// 示例11
setTimeout(function() {
    'use strict'
    console.log('示例11', this); // Window
}, 0)

// 示例12
function func12() {
    'use strict';
    setInterval(function() {
        'use strict';
        console.log('示例12', this); // Window
    }, 1000)
}
复制代码



原文地址:访问原文地址
快照地址: 访问文章快照