箭头函数在class中作为成员方法的表现和问题

336 阅读1分钟

箭头函数如果在class作为成员方法定义,是不会被添加到类的prototype上的,也就是说,伴随每一次类的实例化,箭头函数都将同时被实例化一次

试着做一个简单的测试

class TestArrow {
    arrow = () => {}
}
class TestRegular {
    regular() {}
}
class TestBind {
    constructor() {
        this.bind = this.bind.bind(this);
    }
    bind() {}
}
class TestBind2 {
    constructor() {
        this.bind = function () {}
    }
}

// 然后看看实例化的耗时
let time = Date.now()
for(let i = 0;i<1_000_000;i++) new TestArrow()
console.log(Date.now() - time)

直接贴图看看结果  就是f12在console中测试

可以看到TestArrow类的prototype中并没有arrow方法,而TestRegular的prototype则有regular方法

再试试别的操作

箭头函数果真存在一定程度的性能问题,而对于bind的写法,其实bind返回的新函数,其实内部也是指向prototype链上原来的方法,所以bind的写法还好吧

虽然这个时间差也不能真正说明内存的开销,但箭头函数确实也让实例化对象需要更多的时间。至于TestBind2 原本是期待这个类的

==========更新

不小心刷到一篇文章 zhuanlan.zhihu.com/p/139448894

这里说了,实际上是因为class语法中 = 的写法,实际上就是在声明实例属性,然而要在class中使用箭头函数只能用 = 号了,也就是说,这不是箭头函数的锅