定义这样一个方法:Element.prototype.hide = function() { this.style.display = 'none' }这样做的话,在使用Element的实例调用该该方法时,可以正常绑定this的值。但是,如果改成这样:Element.prototype.hide = () => { this.style.display = 'none' }就会报错,查看babel解析后的代码,发现this没有绑定上:Element.prototype.hide = function() { undefined.style.display = 'none' }查看了MDN以后,MDN告诉我说箭头函数是自动寻找上下文中的this值给自己赋值。对此我感到不解:我这段代码是写在最外层的,那么this的值不应该是window吗?也就是说,即使执行不了,这个函数转化后不应该是如下这样吗:Element.prototype.hide = function() { window.style.display = 'none' }尝试了一下,在外面包裹一层function,将里面的箭头函数做成IIFE,由于获得了上下文,箭头函数可以正常使用了:Element.prototype.show = function() {(() => { this.style.display = 'block' })()}但是这么写就太二了,我本意是想用箭头函数让代码简洁点,这样还不如用一开始的function写法。所以有什么方法能够让箭头函数正常获取到this值呢,或者说定义方法时不能用箭头函数?求各位高手解惑。
添加回答
举报
0/150
提交
取消