React中的事件处理为什么要bind this?
个人总结: ? 问: 请给我讲一下React中的事件处理为什么要bind this? ? ? ? ? 答:好的。好的,比如说我写了一个类组件,有个onClick属性 ,onClick={ this.fun },如果不bind肯定是会炸裂的,下面讲一下为什么要bind this: ? ? 首先我们知道React是通过创建虚拟DOM 然后将虚拟DOM生成真实的DOM 最后插入到页面中, ? ? 而React生命周期中render方法的作用就是将虚拟DOM渲染成真实DOM ? ? ?看一下这篇文章?https://github.com/hujiulong/blog/issues/4 ? ? 这里提到了render的实现 render将"on+大写字母"开头的事件属性 转化为"on+小写字母"开头的属性 并生成真实DOM,生成真实DOM的同时 ? ? 把这个函数赋值过去。??? ? ? 预备知识点:JS中的this是由函数调用者调用的时候决定的。? ? ?obj:{ ? ? ? ?fun:function(){ console.log(this) } ? ? ? }? ? obj.fun()? ?//obj ? let var = obj.fun() ? var()? ? ? // window||undefined ? ? ? ?在类组件的render函数中 将函数fun赋给真实的属性的时候 有点类似于做了这样的操作: ? class Cat { sayThis () { console.log(this); // 这里的 `this` 指向谁? } exec (cb) { cb(); } render () { this.exec(this.sayThis); } } const tom = new Cat(); tom.render(); // 输出结果是什么? ? 当把一个函数作为callback传递给另一个函数的时候,这个函数的this一定是会丢失的, 因为相当于是 let var = fun() { ..} ; var(); 所以会出现这种问题。 ? 延伸一下,为什么React没有自动的把bind集成到render方法中呢? 答:因为render多次调用每次都要bind会影响性能。 ? ========================================================== ? 知乎大佬-dmumatt原回答: ? 代码一: // 使用 ES6 的 class 语法 class Cat { sayThis () { console.log(this); // 这里的 `this` 指向谁? } exec (cb) { cb(); } render () { this.exec(this.sayThis); } } const tom = new Cat(); tom.render(); // 输出结果是什么?
? 代码二: const jerry = { sayThis: function () { console.log(this); // 这里的 `this` 指向谁? },exec: function (cb) { cb(); },render: function () { this.exec(this.sayThis); },} jerry.render(); // 输出结果是什么?
? 代第一段代码的结果是 第二段代码的结果是,你所使用的环境里面的全局对象——在浏览器中就是 你看到输出结果的时候,一定感到很困惑吧?到底 JS 中的
|