Good question with a simple answer: you cannot !
Javascript is a client-side programming language, so it runs on the client machine, so you cannot hide anything from the client.
Obfuscating your code is a good solution, but not enough, because although it is difficult, someone can decrypt your code and "steal" your script.
There are several ways to make your code hard stolen, but since I said nothing, it is bulletproof.
Above my head, one idea is to restrict access to your external js files outside of the page into which you embed your code. In this case, if you have
<script type="text/javascript" src="myJs.js"></script>
and someone is trying to access the myJs.js file in the browser, he should not be granted access to the script source.
For example, if your page is written in php, you can enable the script through the include function and let the script decide whether it is safe to return the source.
In this example, you will need the external js file (written in php) myJs.php:
<?php $URL = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; if ($URL != "my-domain.com/my-page.php") die("/\*sry, no acces rights\*/"); ?>
which will be included in your main page my-page.php:
<script type="text/javascript"> <?php include "myJs.php"; ?>; </script>
Thus, only the browser could see the contents of the js file.
Another interesting idea is that at the end of your script, you delete the contents of your dom script element, so that after the browser evaluates your code, the code will disappear:
<script id="erasable" type="text/javascript"> </script>
All these are just simple hacks that cannot, and I cannot stress this: I cannot completely protect your js code, but they can convince someone who is trying to "steal" your code.
Update:
I recently met a very interesting article written by Patrick Wid on how to hide your js code, and it reveals a different approach: you can encode the source code into an image! Of course, this is also not bullet proof, but this is another fence that you could build around your code.
The idea behind this approach is that most browsers can use the canvas element to process pixels in images. And since the canvas pixel is represented by 4 values โโ(rgba), each pixel can have a value in the range of 0-255. This means that you can store a character (its actual ascii code) in each pixel. The rest of the encoding / decoding is trivial.
Thanks Patrick!