How does a cell know what function it has within an organism?
The answer to this question can be split into two parts: cell differentiation from stem cells and simple mitosis. Also, the answer I am providing mainly only applies to species that sexually reproduce.

During the primary stages of growth, immediately following the fertilisation of the female gamete, the zygote begins to divide. Most of these initial cells will not be specialised, they will be stem cells and these have the potential to asymmeterically divide. When they do this, each of the daughter cells will have a specific specialisation path to follow. Which path they will follow, muscular, neural etc. is determined by transcription proteins.

Once the stem cells have produced the correct daughter cells, the general structure of the organism will begin to take form. Once this happens and the cells have followed their development paths until they hit their final specialisation, mitosis takes over. This means that a muscle cell will divide, causing the organism to grow. A muscle cell, will only ever divide into a muscle cell, the same goes for all specialised cells. This is how an organism grows and maintains itself.

However, some stem cells do remain after the organism has matured. For instance, a mature neuron is unable to undergo mitosis, so stem cells are needed to allow for the production of new neurons to replace those that die, to take one example.

You can find out more here.