The Mew glitch occurs due to a minor programming oversight. When the player steps down towards the Gambler, normally a battle would occur. When the player flies away, however, the battle does not occur. The game does, though, store the data, signaling for a battle occurring near Lavender Town.
When the player fights the Youngster, the battle data for the Gambler is overwritten with the battle data for the Youngster. Due to the way the game reads battle data, the Slowpoke's special stat of 0x15 (21 decimal), or indeed the special stat of your Pokémon the Ditto transformed into (should be 21 to make Mew appear) is placed in the same location that codes for a wild Pokémon.
Returning to Lavender Town, the game attempts to resume the previous battle but using the new data. By accessing the hexadecimal value 0x15, the game loads the battle data for Mew.