给定的 ES6 代码如下
let a = new SomeClass();
let b = new AnotherClass();
let x = a.someMethod.bind(b, 1, 2, 3);
let y = () => a.someMethod.call(b, 1, 2, 3);
x
和 y
之间有什么有意义的区别吗? 我知道 bind()
很多旧函数,但现在是否需要在箭头函数上使用它?
至少对我来说,箭头函数语法比 bind()
语法更容易阅读,尤其是因为在实践中你通常可以避免使用 call()
this
仍然具有词法上下文中的正常含义。例如,bind()
在实践中是否会有更好的性能(CPU 或 RAM)?
最佳答案
let a = function(){};
let b = function(){};
a.m = 1
b.m = 2
a.someMethod = function(x, y, z){ return this.m + x + y + z }
let x = a.someMethod.bind(b, 1, 2, 3);
let y = () => a.someMethod.call(b, 1, 2, 3)
console.log( x(1,2,3) )
console.log( y(1,2,3) )
function goBind() {
for (var i = 0; i < 1000000; i++) {
x(1,2,3)
}
}
function goArrow() {
for (var i = 0; i < 1000000; i++) {
y(1,2,3)
}
}
function race() {
var start = performance.now();
goBind();
console.log('bind: ' + (performance.now() - start));
start = performance.now();
goArrow()
console.log('arrow: ' + (performance.now() - start));
start = performance.now();
goBind();
console.log('bind: ' + (performance.now() - start));
start = performance.now();
goArrow()
console.log('arrow: ' + (performance.now() - start));
console.log('------');
}
<button onclick="race()">RACE!</button>
关于javascript - bind() 与箭头函数 + call() 有什么有意义的区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70973212/