The same way any animal takes care of another member of it's social group in the wild or in captivity. There's tons upon tons of documented accounts. They can sense emotions and intent to some extent. Body language, hormones. There are numerous instances where say, a gunmen comes in to rob a store, and the dog knows immediately from the man's gestures and his owner's response to attack him. Or if a child molester pops out to abduct a little girl walking her dog, the dog will more than likely attack him. Numerous stories of dogs pulling drowning children out of water to safety.
As for cats, they live more solitary lives, but through domestication they do become more dependent. They see us largely as both their mother and their kitten. My cats for instance always sleep on me when I'm sick, one of them seems intent on calming me down whenever I seem pissed off about something. She's attacked other animals after I've been scratched by them, and when I become upset with a friend or family member, their whole demeanor towards them changes, and they'll hiss at them and not want a thing to do with them.
I think a lot of it is mimicking our behavior and assuming that's how they're supposed to behave. I certainly wouldn't claim there was some deep, profound thought process at work, and it's even debated they feel emotions to the same extent we do, and not beyond "food good" but they make it damned easy to humanize them.