zoukankan      html  css  js  c++  java
  • 改变this 指向的3种方法

    1.在函数内部声明一个that,然后将this赋值给that,

    var that=this;
    最后用that 代替this使用
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        
    </body>
    <script>
        const team={
            members:["Herry","hrll"],
            teamName:"Es6",
            teamSummary:function() {
                var that=this;
                return this.members.map(function(member) {
                    return `${member}隶属于${that.teamName}`
                })
            }
        }
        console.log(team.teamSummary())
    </script>
    </html>

    2.用bind方法,绑定外部的this

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        
    </body>
    <script>
        const team={
            members:["Herry","hrll"],
            teamName:"Es6",
            teamSummary:function() {
                
                return this.members.map(function(member) {
                    return `${member}隶属于${this.teamName}`
                }.bind(this))
            }
        }
        console.log(team.teamSummary())
    </script>
    </html>

    3.直接使用箭头函数

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        
    </body>
    <script>
        const team={
            members:["Herry","hrll"],
            teamName:"Es6",
            teamSummary:function() {
                
                return this.members.map((member)=> {
                    return `${member}隶属于${this.teamName}`
                })
            }
        }
        console.log(team.teamSummary())
    </script>
    </html>

    3个显示效果:

  • 相关阅读:
    光盘和U盘
    解决时间同步
    僵尸进程 和 孤儿进程
    Centos虚拟机设置网络模式
    常用CDN 和 后台管理模板
    微信小程序wxs如何使用
    kubernetes/client-go--使用 Clientset 获取 Kubernetes 资源对象
    samplecontroller
    volcano
    DNS欺骗
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/9638639.html
Copyright © 2011-2022 走看看