• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 282
  • Last Modified:

Having trouble understanding javascript bind

I took a look at the following url and explanation but still don't get it


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Can somebody explain it better to me
0
stargateatlantis
Asked:
stargateatlantis
  • 3
  • 3
1 Solution
 
Göran AnderssonCommented:
When you call a function as a method of an object, the context of the method is the object, and you can access the object using the this keyword.

Example:

var obj = {
  info: 'asdf',
  fn: function(){
    alert(this.info);
  }
};

obj.fn(); // alerts "asdf"

Open in new window


The bind method allows you to create a function reference that will act as if you called it as a method in an object, without the function actually being part of the object.

Example:

var obj = {
  info: 'asdf'
};

function showInfo() {
  alert(this.info);
}

var f = showInfo.bind(obj);
f(); // alerts "asdf"

Open in new window

0
 
stargateatlantisAuthor Commented:
Can you bind a object that contains a function??
0
 
Göran AnderssonCommented:
Yes, you can use any object as context for the function.

You could even use something like "a string" or 42 as context, then the context would be a String object or a Number object, respectively.

If you would use null or undefined as context, the function would get the window object as context.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
stargateatlantisAuthor Commented:
is there a more complex example
0
 
Göran AnderssonCommented:
Here is an example with an object constructor and binding a function to an instance of the object:

function Employee(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

Employee.prototype = {

  showName: function(){
    alert(this.firstName + ' ' + this.lastName);
  }

};

// create an emplyee and show the name
var john = new Employee('John', 'Doe');
john.showName();

//bind a function expression to the employee
var showNameReverse = (function(){
  alert(this.lastName + ', ' + this.firstName);
}).bind(john);

// use it
showNameReverse();

Open in new window

0
 
stargateatlantisAuthor Commented:
Thanks for the help that is what I was looking for
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now