javascript - React里面的这个bind(this)是什么意思?
天蓬老师
天蓬老师 2017-04-11 11:53:55
[JavaScript讨论组]

求详解。。

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(4)
怪我咯

题主想知道的应该是这里为什么要用bind。

  1. 首先bind就是改变函数运行时的this,详细请看bind

  2. 你的代码中调用了setInterval(fun, time),其实等同于window.setInterval(fun, time)

  3. 如果没调用bind(this),那么传入setInterval中的fun的this指向是setInterval的调用者window对象

  4. 给函数bind(this),这里的this指向就是componentDidMount()中的this也就是这个react对象,这样才能够正确访问react属性方法this.state,this.setState等

天蓬老师

就是把外面(componentDidMount)的this传到内部(timer),跟很多人喜欢在外面定义一个that,里面用that来指向外部的this是一个道理。这个跟react没有关系,是js的基础,你可以去看看js的bind, call, apply。

怪我咯

bind可以改变函数内部this的指向,此外还可以想函数传递数据,参数arguments
例如

onChange={this.changeValue.bind(this,'value')}

这个的话,这个函数就可以这样写了

changeValue(str){
console.log(str)  //'value'
}
巴扎黑

文档上是这么写的

Function.prototype.bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

大概意思就是绑定函数调用时的this.
ECMAScript 5.1增加的特性,与React无关

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号