Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing javascript instance member when passing the method

I wrote some code like this

function Flasher() {
    this.cards = []
    this.map = {
        14: this.flip
    }
}
Flasher.prototype.flip = function() {
    alert(this.cards.length)
}
flasher = new Flasher()
flasher.map[14]()

Unfortunatley, the this object becomes the map object within the flip method and an error occurs (because cards is undefined).

How can I get this to function as intended? Calling flip indirectly via map is necessary, but I would like access to the original object within flip.

like image 967
Fletcher Moore Avatar asked May 15 '26 08:05

Fletcher Moore


1 Answers

function Flasher() {
    var self = this;

    this.cards = [];
    this.map = {
        14: function() { self.flip(); }
    };
}
like image 84
John Kugelman Avatar answered May 16 '26 21:05

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!