The Serb won 6-4 5-7 6-4 6-4 in New York, and will end the year with three of the four tennis majors.
Djokovic, 28, held his nerve in front of a heavily pro-Federer crowd at Flushing Meadows.
The 34-year-old Swiss had been hoping to win his 18th major title and first for three years.
In a raucous New York night session atmosphere on Arthur Ashe Stadium, after the start of play was delayed by more than three hours because of rain, Federer looked to have a real chance in the third set.
However, Djokovic broke the Federer serve six times and saved 19 of 23 break points as he battled his way to a 27th win in 28 Grand Slam matches this year.