javascript this指向问题你知多少,es5/es6解决方案是什么?

es5 this指向问题处理方式

采用bind方法解决this指向问题

import React from 'react';
import ReactDom from 'react-dom';

class App extends React.Component{
    constructor(){
        super();
        this.state={
            stateTitle:"初始化标题"
        }
    }
    changeStateTitle(){
        this.setState({stateTitle:"更新后的标题"},()=>{
            console.log(this.state.stateTitle);
        });
    }
    render(){
        
        return (
            <div className="App">
				{{this.state.stateTitle}}
                <button type="button" onClick={this.changeStateTitle.bind(this)}>改变标题</button>
            </div>
        )
    }
}

export default App;

bind(this)问题原理

我们用一个简单的html页面来测试这个问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>this指向</title>
</head>
<body>
<script>
    function Obj(){
        this.name="张三";
        this.init();
    }
    Obj.prototype.init=function(){
        console.log(this);
         var _this=this;
         document.addEventListener("click",function(){
             console.log(this);
             console.log(_this.name);
         })
    }
    new Obj();
</script>
</body>
</html>

点击页面前控制台输出
点击网页后触发click事件
可以看出:
(1)初始化加载Obj.prototype.init=function(){}中this指向document
(2)click事件执行,thiis指向document
(3)只有规避java script this名字,另外传递一个变量名称,才能将所需要传递的值,传递到回调函数

基于此,javascript还有个bind方法可以解决此问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>this指向</title>
</head>
<body>
<script>
    function Obj(){
        this.name="张三";
        this.init();
    }
    Obj.prototype.init=function(){
        console.log(this);
        var _this=this;
        document.addEventListener("click",function(){
            console.log(this);
            console.log(this.name);
        }.bind(this))
    }
    new Obj();
</script>
</body>
</html>

es6 优雅的解决方案

而如果想优雅解决此问题,es6有个新功能,便是箭头函数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>this指向</title>
</head>
<body>
<script>
    function Obj(){
        this.name="张三";
        this.init();
    }
    Obj.prototype.init=function(){
        console.log(this);
        // var _this=this;
        // document.addEventListener("click",function(){
        //     // console.log(this);
        //     console.log(this.name);
        // }.bind(this))
        document.addEventListener("click",()=>{
            console.log(this);
            console.log(this.name);
        })
    }
    new Obj();
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值