在设置上下文时,使用bind的替代方法是什么?

What is the alternative to using bind when setting context?

本文关键字:方法 是什么 bind 上下文 设置 使用      更新时间:2023-09-26

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

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函数()将被弃用。是jQuery绑定函数还是JavaScript绑定函数将被弃用?

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

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

没有问题,因为你用的不是$.bind,而是Function.prototype.bind

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

Function.prototype.bind未被弃用。你的代码大部分很好,除了

下面的异常

关于代码的一些注意事项

// 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 -箭头函数有一个词法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());
  }
};

您目前可以使用$.proxy()。尽管$.proxy()在未来的jQuery版本中也可能被弃用。

$( 'input' ).on( 'click', $.proxy( this.log, this ) )