Well, because Mg removes 2 of its valence electrons to achieve its octet of 8 Valence electrons in its outer shell, by donating to oxygen, which like Mg also wants to achieve chemical reactive stability and does this by receiving these 2 valence electrons from Mg. These two atoms now form into ions and then held together by an electrostatic attraction between the positive Mg ion and negative O ion. This is an example of an ionic bond.