有如下一小段代码,能否发现这里有什么问题?
const math = { sin(val){ return Math.sin(val); }, cos(val){ return Math.cos(val); }, tan(val){ const sin = this.sin ; const cos = this.cos ; return sin(val)/cos(val); }, }; 一个粗心的程序员可能会这么续写
const { sin , cos , tan } = math ; console.log( tan(.5) ); 这里就会报错了,因为 tan 方法内部需要的 this 对象在解构赋值的时候丢失了。要想正确使用,必须把代码写成这样的丑陋形式
let { sin , cos , tan } = math ; [ sin , cos , tan ] = [ sin , cos , tan ].map( e => e.bind(math) ); console.log( tan(.5) ); 不过,其实只要在开始的时候,把这两行
const sin = this.sin ; const cos = this.cos ; 写成
const sin = math.sin ; const cos = math.cos ; 这样,就消除了隐患。显然,对于 tan 方法,动态绑定 this 对象是没有意义的,因为这个值既不会也不允许改变
总结一下就是,this 是针对动态绑定需求设计的,如果没有这个需求,就不要强行使用,哪怕表面上看上去很优雅

