这篇“JS中不应该使用箭头函数的情况有哪些”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“JS中不应该使用箭头函数的情况有哪些”文章吧。
在箭头函数中,我们不能像在普通函数中那样使用 arguments 对象。
const fn1 = () => {
console.log('arguments', arguments)
}
fn1('fatfish', 'medium')
function fn2(){
console.log('arguments', arguments)
}
fn2('fatfish', 'medium')
可以看到,fn1箭头函数报错,但是fn2可以正常读取arguments对象。
我们如何才能在箭头函数中获取所有传递给函数的参数?
是的,没错,你可以使用Spread Operator来解决它。
const fn3 = (...values) => {
console.log('values', values)
}
fn3('fatfish', 'medium')
我相信你可以很容易地知道下面的代码会输出什么。
const fn1 = () => {
console.log('this-fn1', this)
}
fn1()
function fn2(){
console.log('this-fn2', this)
}
fn2()
{
name: 'fatfish'
}
我们希望 fn1 和 fn2 都打印对象,我们应该怎么做?
代码:
const thisObj = {
name: 'fatfish'
}
const fn1 = () => {
console.log('this-fn1', this)
}
fn1.call(thisObj)
function fn2(){
console.log('this-fn2', this)
}
fn2.call(thisObj)
因为箭头函数在定义的时候就决定了它的this指向谁,所以没有办法用fn1.call(thisObj)再次改变它。
箭头函数不是万能的,至少有 4 种情况我们不应该使用它们。
function Person (name, age) {
this.name = name
this.age = age
}
const Person2 = (name, sex) => {
this.name = name
this.sex = sex
}
console.log('Person', new Person('fatfish', 100))
console.log('Person2', new Person2('fatfish', 100))
为什么 new Person2 会抛出错误
因为构造函数通过 new 关键字生成一个对象实例。生成对象实例的过程也是通过构造函数将this绑定到实例的过程。
但是箭头函数没有自己的this,所以不能作为构造函数使用,也不能通过new操作符调用。
我们经常在 click 事件中通过 this 读取元素本身。
const $body = document.body
$body.addEventListener('click', function () {
// this and $body elements are equivalent
this.innerHTML = 'fatfish'
})
但是如果你使用箭头函数给 DOM 元素添加回调,这将等同于全局对象窗口。
const $body = document.body
$body.addEventListener('click', () => {
this.innerHTML = 'fatfish'
})
const obj = {
name: 'fatfish',
getName () {
return this.name
},
getName2: () => {
return this.name
}
}
console.log('getName', obj.getName())
console.log('getName2', obj.getName2())
你知道这段代码会输出什么吗?
是的,getName2方法不会打印“fatfish”,因为此时this和window是等价的,不等于obj。
const Person = function (name) {
this.name = name
}
Person.prototype.showName = function () {
console.log('showName', this, this.name)
}
Person.prototype.showName2 = () => {
console.log('showName2', this, this.name)
}
const p1 = new Person('fatfish', 100)
p1.showName()
p1.showName2()
以上就是关于“JS中不应该使用箭头函数的情况有哪些”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。