javascript - 设置上下文时使用绑定(bind)的替代方法是什么?

标签 javascript jquery bind

到目前为止,我一直在我的网络应用程序中使用以下语法。

function.bind( obj );

所以假设我有一个像这样的对象:

myObj = {
    msg: 'You have logged ',
    init: function(){
        $( 'input' ).on( 'click', this.log.bind( this ) ),
    },
    log: function( e ){
        console.log( this.msg + $( e.target ).val() );
    }
}

我可以调用init函数。 myObj.init();

但问题是我读到 .bind function() 将被弃用。是 jQuery 绑定(bind)函数还是 JavaScript 绑定(bind)函数将被弃用。

如果这将是即将被弃用的 JavaScript 函数,那么它的替代方案是什么?

最佳答案

But the problem is i read that the .bind function() will be deprecated. Is that the jQuery bind function or the JavaScript bind function that is going to be deprecated.

没有问题,因为您没有使用 $.bind,而是使用 Function.prototype.bind

If that is going to be the JavaScript function that is going to be deprecated then what is its alternative ?

Function.prototype.bind 并未被弃用。您的代码大部分都很好,除了下面的异常(exception)

<小时/>

有关代码的一些注意事项

// no `var`, `let` or `const` keyword
myObj = {
  msg: 'You have logged ',
  init: function(){
    // event handlers usually pass an `event` object
    $( 'input' ).on( 'click', this.log.bind( this ) ),
  },
  log: function(){ // no `e` param here
    console.log( this.msg + $( e.target ).val() );
  }
}

可以更新为

var myObj = {
  msg: 'You have logged ',
  init: function(){
    $( 'input' ).on( 'click', this.log.bind( this ) ),
  },
  log: function(e){
    console.log( this.msg + $( e.target ).val() );
  }
}
<小时/>

还有一种使用 ES6 表达代码的完全替代方式 – arrow functions有一个词法 this,因此此示例中不需要 Function.prototype.bind

const myObj = {
  msg: 'You have logged ',
  init () {
    $('input').on('click', event => this.log(event));
  }
  log (event) {
    console.log(this.msg, $(event.target).val());
  }
};

关于javascript - 设置上下文时使用绑定(bind)的替代方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39577716/

相关文章:

c++ - 为什么在 C++14 中使用 std::bind 而不是 lambda?

javascript - ng-model 没有在单选按钮中更新

javascript - 仅过滤可见的单选按钮

jquery - IE9 中的 JPlayer 问题

Angular 9 |无法绑定(bind)到 'loading',因为它不是 'img' 的已知属性

jQuery 两个 mouseenter 事件,触发一个函数一次

javascript - 错误 : Components. utils undefined - Firefox 附加组件

javascript - 从 HTML 中的动态表中获取单元格值

javascript - React 组件不会显示函数的返回

javascript - 如何让一个div全屏?