Function.bind

written in javascript

Hi guys,

In most projects that I work in some moment I need to change the scope of a execution of any function in javascript.

For example: I need to change a content of any element in my HTML in a asynchronous request, but the scope of this asynchronous request is somewhere I donĀ“t know, so i use a bind prototyped function of a Function native object to change or set the scope for me like this:

.bind()
1
2
3
4

$.get(function(data){
  this.elemente.innerHTML = data;
}.bind(this))

Look at .bind after the function, that instruction set my scope for execution of this function, the scope is this.

To do this, I stole the prototype function from a prototypeJS framework and adapted it for my needs.

You can also send more arguments for a function. In the bind function, the first argument is a scope and the others are the function arguments. I can do so:

send arguments for a function
1
2
3
4
5
var test = function (foo, bar){
  this.log(arguments);
  this.log(foo, bar);
}.bind(console, 'foo', 'bar');
// in console you can view 'foor', 'bar' log

That’s all folks, this is the javascript trick for today. Thanks.


Comments