Last active
July 25, 2016 21:44
-
-
Save pierreozoux/10253594 to your computer and use it in GitHub Desktop.
Issue in context - how to solve that?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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'
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
globalizenew Car("blue");