Pass an object’s function to another of its functions

This is what I have:

var Person = function(fname, lname) {
  this.fname = fname;
  this.lname = lname;
};

Person.prototype = {
  getFullName: function() {
      return this.fname + " " + this.lname;
  },
  doStuff: function(stuff) {
      return stuff();
  }
};

var john = new Person("John", "Doe");

The doStuff function works with other functions, but doing the following returns undefined undefined:

console.log(john.doStuff(john.getFullName));

What’s wrong with what what I have and how can I change it to make it work? Thanks.


solution

It’s because this doesn’t refer to the object.

You could use the .bind() method in order to set the value of this:

john.doStuff(john.getFullName.bind(john));

However, that’s not very flexible, therefore you could just bind it within the doStuff method:

doStuff: function(stuff) {
  return stuff.apply(this);
}