user2146323 user2146323 - 2 months ago 8
Javascript Question

What is the alternative to using bind when setting context?

i have been using the following syntax in my web app so far.

function.bind( obj );


So given i have an object like:

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


I can call the
init
function.
myObj.init();

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.

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

Answer

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.

There is no problem because you're not using $.bind, you're using 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 is not being deprecated. Your code is mostly fine, less the exceptions below


Some things to note about your code

// 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() );
  }
}

Could be updated to

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() );
  }
}

And a completely alternative way to express the code using ES6 – arrow functions have a lexical this so no Function.prototype.bind is required in this example

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