博客
关于我
对于js中的this指向的深入理解
阅读量:381 次
发布时间:2019-03-05

本文共 1546 字,大约阅读时间需要 5 分钟。

this指向详解

1. this的指向规则

this的指向是 JavaScript 中一个非常重要的概念,它决定了在函数中哪个对象会被用来访问变量、方法和属性。在不同的调用方式下,this的指向会发生变化。以下是几种常见的 this 指向规则:

  • new绑定

    当函数被用 new 调用时,this 指向的是新创建的对象。如果构造函数没有返回值,this 指向新对象;如果返回值是一个对象或函数,则this指向返回值。

  • 显式绑定

    使用 callapplybind 方法手动指定 this 的值。如果传入 nullundefined,严格模式下 this 为传入值,非严格模式下按默认规则绑定全局对象。

  • 隐式绑定

    函数在对象属性上直接调用,如 obj.func(),此时 this 指向 obj

  • 默认绑定

    当没有其他绑定规则适用时,this 绑定为调用函数的上下文对象。在严格模式下,thisundefined,否则为全局对象。

  • 箭头函数

    箭头函数没有自己的 this,它继承外层上下文的 this


  • 2. this指向的面试题总结

    如何判断 this 的指向?

  • 判断是否为 new 绑定:如果函数被 new 调用,则 this 指向新对象(返回值为对象或函数时除外)。

  • 判断是否为显式绑定:如果函数使用 callapplybind 手动指定 this,则 this 指向指定对象。

  • 判断是否为隐式绑定:如果函数在对象属性上调用,如 obj.func(),则 this 指向对象 obj

  • 默认绑定:如果以上均不适用,则 this 绑定为调用上下文对象(严格模式下为 undefined)。

  • 特殊情况:若 callapplybind 传入 nullundefined,严格模式下 this 为传入值,否则按默认规则绑定全局对象。


  • 3. 实际案例分析

    案例1:默认绑定

    var age = 28;function info4() {    console.log(this.age);}info4(); // 严格模式下:this 为 undefined,非严格模式下:this 为 window 或 global

    案例2:显式绑定

    var person3 = {    age: 26,    info: function() {        console.log(this.age);    }};var info = person3.info.bind(person3)();// 调用 bind 后,this 指向 person3

    案例3:隐式绑定

    var person5 = {    age: 26,    info3: function() {        console.log(this.age);    }};person5.info3(); // this 指向 person5

    案例4:箭头函数

    let obj = {    age: 27,    info: function() {        return () => {            console.log(this.age); // 这里的 this 指向 obj        }    }};let info5 = obj.info();info5(); // 输出 27

    4. 总结

    this 的指向是 JavaScript 开发中必须深入理解的核心概念。通过 new、显式绑定、隐式绑定和默认绑定等规则,可以准确判断 this 的值。尤其是在面试中,能够灵活运用这些规则来分析函数调用上下文,能够大大提升你的代码写作能力和问题解决能力。

    转载地址:http://capg.baihongyu.com/

    你可能感兴趣的文章
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>
    npm scripts 使用指南
    查看>>
    npm should be run outside of the node repl, in your normal shell
    查看>>
    npm start运行了什么
    查看>>
    npm WARN deprecated core-js@2.6.12 core-js@<3.3 is no longer maintained and not recommended for usa
    查看>>
    npm 下载依赖慢的解决方案(亲测有效)
    查看>>
    npm 安装依赖过程中报错:Error: Can‘t find Python executable “python“, you can set the PYTHON env variable
    查看>>
    npm.taobao.org 淘宝 npm 镜像证书过期?这样解决!
    查看>>