ES6的箭头函数,在咱们平常的开发中,增长了不少的方便,ES5须要写三行代码实现的逻辑,使用箭头函数,也许只须要一行,代码开起来清晰、干练!可是,在某些时候,使用箭头函数也会给咱们带来意想不到的麻烦。javascript
在正式开始以前,先来回顾一下,关于箭头函数须要注意的地方:java
话很少说,先上代码!数组
let arr
const obj = {
arr: [1,2,3],
sun:()=>{
console.log(this === window) // true
this.arr.filter(itme=>item+1)
}
}
obj.sun() // Uncaught TypeError: Cannot read property 'filter' of undefined
复制代码
很明显,浏览器会报错,此时的this === window ,可是在全局定义的arr为undefined! 总结:箭头函数会将做用域绑定到window对象!若是须要调用对象上的某个属性时,不能使用箭头函数。 解决方法:浏览器
const obj = {
arr: [1,2,3],
sun(){
console.log(this === obj) // true
this.arr.filter(itme=>item+1)
}
}
obj.sun()
复制代码
function Myfunc(name){
this.name = name;
}
Myfunc.prototype.sayName = ()=>{
console.log(this === window) // true
return this.name
}
const me = new Myfunc('hanson')
me.sayName() // ''
复制代码
此时的this一样也指向的window,这种状况,一样不适合使用箭头函数。使用传统方式,便可完成调用。函数
function Myfunc(name){
this.name = name;
}
Myfunc.prototype.sayName = function(){
return this.name
}
const me = new Myfunc('hanson')
me.sayName() //'hanson'
复制代码
this的一大特性是,能够根据调用函数的方式更改上下文。也就是说,this指向使用时的对象。可是,箭头函数的this值是固定的。实际上是,在箭头函数中,根本不存在this值,致使内部的代码块就是外部的代码块。this值的固定,在某些须要动态绑定的地方,就变得再也不方便了。ui
const button = document.getELementById('myButton');
button.addEventListener('click',()=>{
console.log(this === window);
this.innerHTML = 'click button';
})
复制代码
在全局上下文中,this指向window。当点击事件发生的时候,浏览器尝试使用按钮上下文调用处理函数,可是箭头函数不会更改气预约义的上下文,this.innerHTM至关于window.innerHTML,没有任何意义。this
在上面的注意事项中,咱们提到了。箭头函数不能应用在构造函数中。spa
const Message = (text)=>{
this.text = text;
}
const msg = new Message('message add') //Uncaught TypeError: Message is not a constructor
复制代码
在建立构造函数的时候,不能使用构造函数。由于,在使用构造函数建立对象实例时,构造函数的上下文是新建立的实例对象。prototype
构造函数在某些时候的确能够减小代码量,使开发更加简便。由于箭头函数能够省略括号和大括号,甚至能够省略return。可是在某些时候,若是你的同时跟你配合开发或者在阅读你写的代码时,可能会形成必定的困难。rest
若是文章对你有一点帮助,不要忘记点赞关注哦!