The best answer is that you should spend a couple of hours reading the first 20 pages or so of Sets for Mathematics. This should clarify everything enormously, and I can only sketch the story here. But anyway, that story goes something like this:
There's two different paradigms at work here. In one paradigm (called "material set theory"), functions do not have unique codomains, because codomains are weird and artificial in that framework. In the other paradigm (called "structural set theory"), functions do have unique codomains, because codomains are built very deeply into the foundations of that framework and there's simply no way to get rid of them.
Let me elaborate a bit.
From the perspective of material set theory, sets can overlap in all sorts of complicated ways, e.g. we have $\mathbb{C} \supseteq\mathbb{R}$. This means, for example, that whether we have $\cos_{\mathbb{R}} : \mathbb{R} \leftarrow \mathbb{R}$ or $\cos_{\mathbb{R}} : \mathbb{C} \leftarrow \mathbb{R}$ is (forgive the pun) immaterial and irrelevant, and we can safely ignore the distinction. So in this framework, the whole concept of a codomain can be safely ignored.
However, from the perspective of structural set theory and/or category theory, sets "float free" in the universe, and they don't have apriori inclusions; so for example, its not really correct to say "it holds that $\mathbb{C} \supseteq \mathbb{R}$," because $\mathbb{C} \supseteq \mathbb{R}$ is not a boolean (truthvalue). What's really going on, under this view, is that there's a unique homomorphism of $\mathbb{R}$-algebras of type $\mathbb{C} \leftarrow \mathbb{R},$ call it $\mathbb{C} \supseteq \mathbb{R}.$ Hence, we have:
$$\cos_{\mathbb{R}} : \mathbb{R} \leftarrow \mathbb{R}, \qquad (\mathbb{C} \supseteq \mathbb{R}) \circ \mathrm{cos}_\mathbb{R} : \mathbb{C} \leftarrow \mathbb{R}$$
By an abuse of notation, we sometimes omit the $(\mathbb{C} \supseteq \mathbb{R})$ and wind up with a situation where $\mathrm{cos}_\mathbb{R}$ appears to have two different codomains, but strictly speaking, these are different functions.
Anyway, like I said, you really have to run off and read the first 20 pages or so of Sets for Mathematics (or a similar book) for this to all make sense.