user3240208 user3240208 - 2 months ago 16
Javascript Question

How to use bind function on an anonymous function

I'm not sure why my code isn't running, can someone give me some direction?
When I run this code and check the console I get the error

" Uncaught TypeError: (intermediate value)(intermediate value)(intermediate value) is not a function "

var person = {
firstName: "Jane",
lastName: "Doe",
getFullName: function() {
var fullName = this.firstName + this.lastName;
return fullName;
}
}

(function() {
console.log(this.getFullName());


}).bind(person);

Answer

The problem is that you're missing a semicolon (;). Without the semicolon at the end of your person declaration, your code effectively translates to this.

var person = { firstName: 'Jane', ... }(function() {
  console.log(this.getFullName());
}).bind(person);

Syntactically, you're attempting to call an object as a function then use the result of that function as another function.

Here's your corrected code:

var person = {
  firstName: "Jane",
  lastName: "Doe",
  getFullName: function() {
    var fullName = this.firstName + this.lastName;
    return fullName;
  }
};

// Isn't called because `bind` returns a new function
(function() {
  console.log(this.getFullName());
}).bind(person);

// What you probably want to do
(function() {
  console.log(this.getFullName());
}).call(person);

Comments