javascript - bind() 与箭头函数 + call() 有什么有意义的区别吗?

标签 javascript

给定的 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);

xy 之间有什么有意义的区别吗? 我知道 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>

基于此:Are arrow functions faster (more performant, lighter) than ordinary standalone function declaration in v8?

关于javascript - bind() 与箭头函数 + call() 有什么有意义的区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70973212/

相关文章:

javascript - 在 graphql 的解析器中获取用户代理访问权限

javascript - npm bin 脚本未在 Windows 中正确创建

javascript - 在javascript数组中访问具有特殊字符的格式化值

javascript - 我可以在 Node.js 中捕获控制台输出吗?

javascript - 使用map()将json数据转换为对象

javascript - 日期选择器限制当前年份

javascript - 当我们只需添加属性时为什么要使用原型(prototype)

javascript - 根据下拉选择显示和隐藏

javascript - 一个模块 : OPTIMIZER FAILED: InternalError: missing name after . 运算符(operator)的 Dojo 构建失败

javascript - 有什么办法可以让 JavaScript 可以使用单独程序生成的值吗?