Loading

关于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)
posted @ 2021-02-28 22:50  虚伪渲染敷衍  阅读(412)  评论(0编辑  收藏  举报