You will see the ad is rendered in a sandboxed iframe.
It's true that the ad-network can usually run in the context of the main page, but the ad itself cannot.
The ad network is typically fairly trusted - they are profitable businesses with a lot to lose to lawsuits if they store or leak your password.
It's the ad itself that you shouldn't trust - anyone with $1 can submit an ad. And that's why it's sandboxed.
This has been demonstrated to be wrong (see: every time there's malware on an ad network).
The malware has been in an ad creative, and those are sandboxed. The malware has usually exploited weaknesses in the browser, but if there weren't browser exploits, it still wouldn't get access to the host page.
Such browser exploits are getting harder to find with things like per-domain processes isolation in Chromium based browsers.