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 @   虚伪渲染敷衍  阅读(427)  评论(0编辑  收藏  举报
编辑推荐:
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
阅读排行:
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 提示词工程师自白:我如何用一个技巧解放自己的生产力
· 一文搞懂MCP协议与Function Call的区别
· 如何不购买域名在云服务器上搭建HTTPS服务
点击右上角即可分享
微信分享提示
主题色彩