My book gives the following definition:
A function $f$ from $A$ to $B$ is defined as $f\subseteq A\times B$ such that if $(a,b)\in f$ and $(a,b_1)\in f$ then $b=b_1$ and there exists a $(a,b)\in f$ for each $a \in A$ .
Now according to this definition, the function would be the same even if the codomains are different. Is it true?
Yes. You can change th codomain, and as long as it includes the range of $f$, the function is the same.
For example, $\sin\colon\Bbb R\to\Bbb R$ and $\sin\colon\Bbb R\to[-1,1]$ are the same function. Or $f(1)=1$ is the same whether or not $f\colon\{1\}\to\Bbb N$ to $f\colon\{1\}\to\{0,1\}$.
As the other answers indicate, in some contexts a function is a triplet where the codomain is specified explicitly. It can be useful to know the codomain as part of the function. In set theoretic contexts, it is sometimes better to treat a function as a set of ordered pairs with a certain property.
Why is it useful? For example, it dispenses the need to talk about "canonical injection", and we can just talk about inclusion. Now we can say that $f\subseteq g$ when $g$ is a larger function, or that $f\cap g$ is a function. It allows us to define partial functions more easily, especially in the context of predicate logic: we can define a predicate which is a function on its domain, and it is not necessary this domain is the entire universe of the structure (so the predicate cannot be a function symbol). This is very useful, for example, in computability theory.