神出鬼没的this
神出鬼没的this 上一篇 挖了个坑,今天给补上 你是不是也曾像我一样: 编写了个函数明明可以正常工作,但是一做为事件回调函数就报 undefind 了 在编写React组件时,看到在构造函数中还得对每个方法bind一下 : this.funOne = this.funOne.bind(this); this.funTwo = this.funTow.bind(this); 多么奇怪的写法,为啥子还要再bind下呢? 不如删了,然后就各种 undefined 了 要理解为什么会 undefined 还得从 this 说起: var name = 'tianlang'; function getName() { console.log(this.name); } getName(); 这段代码会输出: tianlang 我们只需加一行看是不相关的代码,就能让它报 undefined : var name = 'tianlang'; function getName() { 'use strict' console.log(this.name); } getName(); VM412:4 Uncaught TypeError: Cannot read property 'name' of undefined at getName (<anonymous>:4:22) at