zoukankan      html  css  js  c++  java
  • 关于js中this的指向详细总结、分析

    this的指向详细剖析

    function Person (color){
        console.log(this)
        this.color = color
        this.getColor = function () {
            console.log(this)
            console.log(this.color)
        }
        this.setColor = function (color){
            console.log(this)
            this.color = color
        }
    }
    

    当作为函数直接调用时, this => window

    // 当作为函数,直接调用时
    // this ===> 在非严格模式下,全局对象window;  严格模式下是undefiend
    Person('red')   // this => window
    

    当作为构造函数时,this => 构造出的实例对象

    // 当作为构造函数时
    // this ===> 构造出的实例对象
    var fitz = new Person('pink')   // this => fitz
    

    当作为对象的方法调用时,this => 调用方法的那个对象

    // 当作为对象的方法调用时
    // this ===> 调用方法的那个对象
    fitz.getColor()     // this => fitz
    

    使用call、apply、bind方法时,this => 法中指定的对象(传入的第一个参数)

    // 当使用call、apply、bind方法时
    // this ==> 方法中指定的对象(传入的第一个参数)
    var lx = {}
    fitz.setColor.call(lx, 'blue')  // this => lx
    console.log(lx)     // lx {color: "blue"}
    

    函数调用时无任何调用前缀,this => window

    // 函数调用时无任何调用前缀
    // this ==> window
    
    /* 
        原因: 执行func1相当于执行在函数外部执行func2()
    */
    function func1 () {
        function func2 () {
            console.log(this)
        }
        func2()     // 无任何调用前缀
    }
    func1()     // this => window
    

    箭头函数的this, this => 就是外层函数的this

    准确的来说, 箭头函数自己没有this, 在箭头函数中的this会像作用域链一样像外层逐层查找, 箭头函数的this就是它外层函数的this

    // 例子1
    /* 
        这个例子中,箭头函数的this是外层函数test1的this
        外层函数test1的this => window
        所以console.log(this.msg) <=> console.log(window.msg)
    */
    window.msg = '测试箭头函数的this'
    function test1 () {
        (() => {
            console.log(this.msg)
        })()
    }
    test1()  // 测试箭头函数的this
    
    // 例子2
    function test2 () {
        return () => {
            console.log(this.name)
        }
    }
    var obj = {
        name: 'Fitz',
        receiveFunc: test2()
    }
    var receiveFunc = test2.call(obj)
    /* 
        执行完上述语句的状态是:
            - 用call方法显示执行函数test2, 得到一个箭头函数
            - 同时test2的this从window强制绑定后变成obj
    */
    receiveFunc()
    

    注意: 箭头函数的this一旦确定无法更改,但是可以通过改变外层函数的this然后曲线更改箭头函数的this

    // 例子3
    function test3 () {
         return () => {
             console.log(this)
         }
    }
    var obj2 = {}
    var receiveFunc2 = test3()
    receiveFunc2.call(obj2)
    
  • 相关阅读:
    BZOJ 3189. [Coci2011]Slika
    BZOJ3188. [Coci 2011]Upit
    P4304 [TJOI2013]攻击装置
    P3966 [TJOI2013]单词
    P3964 [TJOI2013]松鼠聚会
    BZOJ 3157: 国王奇遇记
    设计模式--策略模式
    SSM整合步骤
    Mybatis笔记二
    Java调用WebService之Axis实现
  • 原文地址:https://www.cnblogs.com/fitzlovecode/p/jsadvanced4.html
Copyright © 2011-2022 走看看