• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ellaha
博客园    首页    新随笔    联系   管理    订阅  订阅
类方法中的this

1,类中

class Dog{
        constructor(name, age) {
            this.name = name
            this.age = age
        }
        cry() {
       console.log(this) // undefined
            console.log(`我的名字是${this.name},我的年龄是${this.age}`)
        }
    }
    const d = new Dog('旺财', 10)
    const x = d.cry
    x() // 此处属于cry的直接调用,类中所有定义的方法,浏览器在运行时,全部加上了 use strict,这才是this为undefined的原因

2,方法

let obj = {
            a: 1,
            b: 2,
            c: function(){
                console.log(this)  // this指向window
            }
        }
        const y = obj.c
        y()

3,严格模式可以局部开启

function a() {
   'use strict'
   console.log(this)  // undefined

}
function b() { console.log(this) // window
}
a() b()

4, show()是函数调用表达式

<body>
    <div id="test"></div>
</body>
<script type="text/babel">
    class Demo extends React.Component {
        constructor(props) {
            super(props)
            this.state = {isHot: true}
        }
        render() {
            const {isHot} = this.state
            return <h1 onClick={this.show()}>今天天气很{isHot ? '炎热': '凉爽'}</h1>
        }
        show(){
            console.log(this)  //此时this指向Demo的实例对象
    }
    }
    ReactDOM.render(<Demo/>, document.getElementById('test'))
    
</script>

情况2:react在内部缓存了一个变量x,直接指向show方法(show()属于类原型上的方法),在点击h1的时候,不再通过组件的实例对象调用show方法,而是直接通过x调用show方法,此时启用严格模式,导致this丢失

在点击h1的时候,调用下show函数

<body>
    <div id="test"></div>
</body>
<script type="text/babel">
    class Demo extends React.Component {
        constructor(props) {
            super(props)
            this.state = {isHot: true}
        }
        render() {
            const {isHot} = this.state
            return <h1 onClick={this.show}>今天天气很{isHot ? '炎热': '凉爽'}</h1>
        }
        show(){
            // show函数放在哪里?---Demo的原型对象上,供实例调用
            // show函数中的this指向谁?---如果show是通过Demo实例调用,那么this就指向Demo的实例对象
            console.log(this)  //undefined
    }
    }
    ReactDOM.render(<Demo/>, document.getElementById('test'))
    
</script>

 

posted on 2022-01-08 15:01  ellaha  阅读(115)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3