Use of the JavaScript 'bind' method -
what use of bind() in javascript?
bind creates new function have this set first parameter passed bind().
here's example shows how use bind pass member method around has correct this:
var button = function(content) { this.content = content; }; button.prototype.click = function() { console.log(this.content + ' clicked'); } var mybutton = new button('ok'); mybutton.click(); var looseclick = mybutton.click; looseclick(); // not bound, 'this' not mybutton - global object var boundclick = mybutton.click.bind(mybutton); boundclick(); // bound, 'this' mybutton which prints out:
ok clicked undefined clicked ok clicked you can add parameters after 1st (this) parameter , bind pass in values original function. additional parameters later pass bound function passed in after bound parameters:
// example showing binding parameters var sum = function(a, b) { return + b; }; var add5 = sum.bind(null, 5); console.log(add5(10)); which prints out:
15 check out javascript function bind more info , interactive examples.
Comments
Post a Comment