Skip to content

Instantly share code, notes, and snippets.

@pierreozoux
Last active July 25, 2016 21:44
Show Gist options
  • Save pierreozoux/10253594 to your computer and use it in GitHub Desktop.
Save pierreozoux/10253594 to your computer and use it in GitHub Desktop.
Issue in context - how to solve that?
function Car(color) {
this.color = color
}
Car.prototype.getColor = function() {
return this.color;
}
car = new Car('blue');
function test(callback) {
console.log(callback());
}
car.getColor() //'blue'
test(car.getColor); //undefined
@soarez
Copy link

soarez commented Apr 9, 2014

You can use .bind in the last line. test(car.getColor.bind(car));

If you opt for the revealing pattern as opposed to the prototype pattern you can avoid using this entirely:

function Car(c) {
  var color = c;

  function getColor() {
    return color;
  }
  car.getColor = getColor;

  return car;
}

var car = new Car('blue');

function test(callback) {
  console.log(callback());
}

car.getColor() //'blue'
test(car.getColor); //'blue'

@pierreozoux
Copy link
Author

This code would work :

function Car(c) {
  var color = c;

  function getColor() {
    return color;
  }

  return {
    color: color,
    getColor: getColor
  };
}

var car = new Car('blue');

function test(callback) {
  console.log(callback());
}

car.getColor() //'blue'
test(car.getColor); //'blue'

I checked this documentation

But thanks a lot for the hint!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment