Humans have a natural ability to predict the behavior of others called folk psychology:
... folk psychology, or commonsense psychology, is a human capacity to
explain and predict the behavior and mental state of other people. ...
Traditionally, the study of folk psychology has focused on how
everyday people—those without formal training in the various academic
fields of science—go about attributing mental states.
That is, folk psychology relies on first determining other people's mental state, and then using that information to predict their behavior. This underlying ability to predict mental state is often referred to in the literature as "mind-reading" (not to be confused with telepathy), or more formally, theory of mind or mentalization.
It seems that humans have some mental model of how other people's minds work, and they use this model to predict their behavior. Note however, that lay people use a model that is not (scientifically) valid - that is, it is not an accurate representation of how minds actually work - and hence predictions often fail. Such mental models are presumably sufficiently accurate in everyday situations to be useful nonetheless.
How humans do this is subject to some debate. The leading mechanism is called theory-theory:
This theory asserts that individuals hold a basic or 'naïve' theory of
psychology ("folk psychology") to infer the mental states of others,
such as their beliefs, desires or emotions. This information is used
to understand the intentions behind that person's actions or predict
That is, according to theory-theory, people have an explicit model - one that they learn through experience, and can articulate and apply explicitly - of other people's minds.
One challenge to theory-theory is that humans are far too adept at mind-reading for an explicit model. A competing implicit mechanism is proposed by simulation theory:
... a theory that holds that humans anticipate and make sense of the
behavior of others by activating mental processes that, if carried
into action, would produce similar behavior. This includes intentional
behavior as well as the expression of emotions. The theory states that
children use their own emotions to predict what others will do.
Therefore, we project our own mental states onto others.
In other words, simulation theory suggests that humans have a way to simulate their own mental state - that is, pretend to be in someone else's shoes - and use that to predict the behavior of others.
As there is much evidence both for and against each theory, a hybrid 2-systems account has also been proposed by eg, Frith & Frith (2008), Apperly & Butterfill (2009).