﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>语源科技BlogJava-agen's space</title><link>http://www.blogjava.net/agen10120216/</link><description>let me do something</description><language>zh-cn</language><lastBuildDate>Mon, 15 Jun 2026 01:50:29 GMT</lastBuildDate><pubDate>Mon, 15 Jun 2026 01:50:29 GMT</pubDate><ttl>60</ttl><item><title>Quick guide to somewhat advanced JavaScript( 转载 )</title><link>http://www.blogjava.net/agen10120216/archive/2007/03/09/102860.html</link><dc:creator>今天不打cs</dc:creator><author>今天不打cs</author><pubDate>Fri, 09 Mar 2007 08:20:00 GMT</pubDate><guid>http://www.blogjava.net/agen10120216/archive/2007/03/09/102860.html</guid><wfw:comment>http://www.blogjava.net/agen10120216/comments/102860.html</wfw:comment><comments>http://www.blogjava.net/agen10120216/archive/2007/03/09/102860.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/agen10120216/comments/commentRss/102860.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/agen10120216/services/trackbacks/102860.html</trackback:ping><description><![CDATA[
		<head>
				<title>Quick guide to somewhat advanced JavaScript</title>
				<meta content="tutorial, advanced javascript, json, article" name="KEYWORDS" />
				<meta name="description" content="advanced javascript tutorial" />
				<link rel="stylesheet" href="articles.css" type="text/css" media="all" />
				<link rel="stylesheet" href="recommendations.css" type="text/css" media="all" />
				<script><![CDATA[

			function sp(link)
			{
				var em =  'serg' + 'io_p' + 'ereira@';
				em += 'ms' + 'n.c' + 'om';
				document.write('<a href="mai' + 'lto:' + em + '">' + link + '</a>);
			}


		]]&gt;</script>
		</head>
		<body>
				<div id="mainContent">
						<h1>Quick guide to somewhat advanced JavaScript</h1>
						<h2>tour of some OO features</h2>
						<div class="author">by <script><![CDATA[p('Sergio Pereira')]]&gt;</script></div>
						<div class="author">last update: February 21<sup>st</sup> 2006</div>
						<h3>Hey, I didn't know you could do that</h3>
						<p>
				If you are a web developer and come from the same place I do, you have probably 
				used quite a bit of Javascript in your web pages, mostly as UI glue. 
			</p>
						<p>
				Until recently, I knew that Javascript had more OO capabilities than I was employing,
				but I did not feel like I needed to use it. As the browsers started to support a more 
				standardized featureset of Javascript and the DOM, it became viable to write more 
				complex and functional code to run on the client. That helped giving birth to the 
				AJAX phenomena.
			</p>
						<p>
				As we all start to learn what it takes to write our cool, AJAXy applications, we begin
				to notice that the Javascript we used to know was really just the tip of the iceberg. 
				We now see Javascript being used beyond simple UI chores like input validation and frivolous 
				tasks. The client code now is far more advanced and layered, much like a real desktop 
				application or a client-server thick client. We see class libraries, object models, 
				hierarchies, patterns, and many other things we got used to seeing only in our server 
				side code.
			</p>
						<p>
				In many ways we can say that suddenly the bar was put much higher than before. It takes 
				a heck lot more proficiency to write applications for the new Web and we need to improve 
				our Javascript skills to get there.
				If you try to use many of the existing javascript libraries out there, like 
				<a href="http://prototype.conio.net/">Prototype.js</a>, 
				<a href="http://script.aculo.us/">Scriptaculous</a>, 
				<a href="http://moofx.mad4milk.net/">moo.fx</a>, 
				<a href="http://bennolan.com/behaviour/">Behaviour</a>, 
				<a href="http://developer.yahoo.net/yui/">YUI</a>, 
				etc you'll eventually find yourself reading the JS code. Maybe because you want 
				to learn how they do it, or because you're curious, or more often because that's the 
				only way to figure out how to use it, since documentation does not seem to be highly 
				regarded with most of these libraries. Whatever the case may be, you'll face some 
				kung-fu techniques that will be foreign and scary if you haven't seen anything like 
				that before.
			</p>
						<p>
				The purpose of this article is precisely explaining the types of constructs that 
				many of us are not familiar with yet.
			</p>
						<h3>Related article</h3>
						<p>
				Prototype.js <a href="http://www.sergiopereira.com/articles/prototype.js.html">documentation</a></p>
						<h3>JSON</h3>
						<p>
				JavaScript Object Notation (<a href="http://www.json.org/">JSON</a>,) is one of the new
				buzzwords popping up around the AJAX theme. JSON, simply put, is a way of 
				declaring an object in javascript. Let's see an example right away and note 
				how simple it is.
			</p>
						<pre class="code">

var myPet = { color: 'black', leg_count: 4, communicate: function(repeatCount){ 
for(i=0;i&lt;repeatCount;i++) alert('Woof!');} };
			</pre>
						<p>
				Let's just add little bit of formatting so it looks more like how we usually find out there:
			</p>
						<pre class="code">

var myPet = {
	color: 'black', 
	legCount: 4, 
	communicate: function(repeatCount){
		for(i=0;i&lt;repeatCount;i++)
			alert('Woof!');
	} 
};
			</pre>
						<p>
				Here we created a reference to an object with two properties (<span class="code">color</span> 
				and <span class="code">legCount</span>) and a method (<span class="code">communicate</span>.) 
				It's not hard to figure out that the object's properties and methods
				are defined as a comma delimited list. Each of the members is introduced by name, followed 
				by a colon and then the definition. In the case of the properties it is easy, just the value 
				of the property. The methods are created by assigning an anonymous function, which we will 
				explain better down the line.
				After the object is created and assigned to the variable <span class="code">myPet</span>, 
				we can use it like this:
			</p>
						<pre class="code">
alert('my pet is ' + myPet.color);
alert('my pet has ' + myPet.legCount + ' legs');
//if you are a dog, bark three times:
myPet.communicate(3);
			</pre>
						<p>
				You'll see JSON used pretty much everywhere in JS these days, as arguments to functions, 
				as return values, as server responses (in strings,) etc.
			</p>
						<h3>What do you mean? A function is an object too?</h3>
						<p>
				This might be unusual to developers that never thought about that, but in JS a function is 
				also an object. You can pass a function around as an argument to another function just like
				you can pass a string, for example. This is extensively used and very handy.
			</p>
						<p>
				Take a look at this example. We will pass functions to another function that will use them.
			</p>
						<pre class="code">

var myDog = {
	bark: function(){
		alert('Woof!');
	}
};

var myCat = {
	meow: function(){
		alert('I am a lazy cat. I will not meow for you.');
	}
};
 
function annoyThePet(petFunction){
	//let's see what the pet can do
	petFunction();
}

//annoy the dog:
annoyThePet(myDog.bark);
//annoy the cat:
annoyThePet(myCat.meow);
			</pre>
						<p>
				Note that we pass myDog.bark and myCat.meow without appending parenthesis 
				<span class="code">"()"</span> to them. If we did that we would not be passing 
				the function, rather we would be calling the method and passing the return value, 
				<span class="code">undefined</span> in both cases here.
			</p>
						<p>
				If you want to make my lazy cat start barking, you can easily do this:
			</p>
						<pre class="code">

myCat.meow = myDog.bark;
myCat.meow(); //alerts 'Woof!'
			</pre>
						<h3>Arrays, items, and object members</h3>
						<p>
				The following two lines in JS do the same thing.
			</p>
						<pre class="code">

var a = new Array();
var b = [];
			</pre>
						<p>
				As I'm sure you already know, you can access individual items in an array 
				by using the square brackets:
			</p>
						<pre class="code">

var a = ['first', 'second', 'third'];
var v1 = a[0];
var v2 = a[1];
var v3 = a[2];
			</pre>
						<p>
				But you are not limited to numeric indices. You can access any member of a JS 
				object by using its name, in a string. The following example creates an empty 
				object, and adds some members by name.
			</p>
						<pre class="code">

var obj = {}; //new, empty object
obj['member_1'] = 'this is the member value';
obj['flag_2'] = false;
obj['some_function'] = function(){ /* do something */};
			</pre>
						<p>
				The above code has identical effect as the following:
			</p>
						<pre class="code">

var obj = {
	member_1:'this is the member value',
	flag_2: false,
	some_function: function(){ /* do something */}
};
			</pre>
						<p>
				In many ways, the idea of objects and associative arrays (hashes) in JS are not 
				distinguishable. The following two lines do the same thing too.
			</p>
						<pre class="code">

obj.some_function();
obj['some_function']();
			</pre>
						<h3>Enough about objects, may I have a class now?</h3>
						<p>
				The great power of object oriented programming languages derive from the use 
				of classes. I don't think I would have guessed how classes are defined in JS 
				using only my previous experience with other languages. Judge for yourself.
			</p>
						<pre class="code">

//defining a new class called Pet
var Pet = function(petName, age){
	this.name = petName;
	this.age = age;
};

//let's create an object of the Pet class
var famousDog = new Pet('Santa\'s Little Helper', 15);
alert('This pet is called ' + famousDog.name);
			</pre>
						<p>
				Let's see how we add a method to our <span class="code">Pet</span> class. We will be using the 
				<span class="code">prototype</span> property that all classes have. The <span class="code">prototype</span> 
				property is an object that contains all the members that any object of the class will have. 
				Even the default JS classes, like <span class="code">String</span>, <span class="code">Number</span>, 
				and <span class="code">Date</span> have a <span class="code">prototype</span> object that we 
				can add methods and properties to and make any object of that class automatically gain this new member.
			</p>
						<pre class="code">

Pet.prototype.communicate = function(){ 
	alert('I do not know what I should say, but my name is ' + this.name);
};
			</pre>
						<p>
				That's when a library like <a href="http://www.sergiopereira.com/articles/prototype.js.html">prototype.js</a> comes in 
				handy. If we are using prototype.js, we can make our code look cleaner (at least in my opinion.)
			</p>
						<pre class="code">

var Pet = Class.create();
Pet.prototype = {
	//our 'constructor'
	initialize: function(petName, age){
		this.name = petName;
		this.age = age;
	},
	
	communicate: function(){
		alert('I do not know what I should say, but my name is ' + this.name);
	}
};	
			</pre>
						<h3>Functions as arguments, an interesting pattern</h3>
						<p>
				If you have never worked with languages that support closures, like Ruby or 
				C#2.0, you may find the following idiom too funky.
			</p>
						<pre class="code">

var myArray = ['first', 'second', 'third'];
myArray.each( function(item, index){
	alert('The item in the position #' + index + ' is:' + item);
});
			</pre>
						<p>
				Whoa! Let's explain what is going on here before you decide I've gone too 
				far and navigate to a better article than this one.
			</p>
						<p>
				First of all, in the above example we are using the prototype.js library, which 
				adds the each function to the Array class. The each function accepts one 
				argument that is a function object. This function, in turn, will be called once 
				for each item in the array, passing two arguments when called, the item and the index 
				for the current item. Let's call this function our iterator function. 
				We could have also written the code like this.
			</p>
						<pre class="code">

function myIterator(item, index){
	alert('The item in the position #' + index + ' is:' + item);
}

var myArray = ['first', 'second', 'third'];
myArray.each( myIterator );
			</pre>
						<p>
				But then we would not be doing like all the cool kids in school, right? 
				More seriously, though, this last format is simpler to understand but causes 
				us to jump around in the code looking for the myIterator function. It's nice 
				to have the logic of the iterator function right there in the same place 
				it's called. Also, in this case, we will not need the iterator function anywhere 
				else in our code, so we can transform it into an anonymous function without penalty. 
			</p>
						<p>
				Let's look at the original example again with some highlighting to hopefully make things clearer.
			</p>
						<pre class="code">
				
var myArray = ['first', 'second', 'third'];
myArray.each( <span style="font-weight:bold;">function(item, index){
	alert('The item in the position #' + index + ' is:' + item);
}</span> );
			</pre>
						<h3>This is this but sometimes this is also that</h3>
						<p>
				One of the most common troubles we have with JS when we start writing our code 
				is the use of the <span class="code">this</span> keyword. It could be a real 
				tripwire.
			</p>
						<p>
				As we mentioned before, a function is also an object in JS, and sometimes we 
				do not notice that we are passing a function around. 
			</p>
						<p>
				Take this code snippet as an example.
			</p>
						<pre class="code">

function buttonClicked(){
	alert('button ' + this.id + ' was clicked');
}

var myButton = document.getElementById('someButtonID');
var myButton2 = document.getElementById('someOtherButtonID');
myButton.onclick = buttonClicked;
myButton2.onclick = buttonClicked;
			</pre>
						<p>
				Because the buttonClicked function is defined outside any object we may tend to
				think the <span class="code">this</span> keyword will contain a reference to 
				the <span class="code">window</span> or <span class="code">document</span> 
				object (assuming this code is in the middle of an HTML page viewed in a browser.)
			</p>
						<p>
				But when we run this code we see that it works as intended and displays the <span class="code">id</span> of
				the clicked button. What happened here is that we made the onclick method of each button contain the 
				<span class="code">buttonClicked</span> object reference, replacing whatever was there before. Now 
				whenever the button is clicked, the browser will execute something similar to the following line.
			</p>
						<pre class="code">

myButton.onclick();
			</pre>
						<p>
				That isn't so confusing afterall, is it? But see what happens you start having other 
				objects to deal with and you want to act on these object upon events like the button's click.
			</p>
						<pre class="code">

var myHelper = {
	
	formFields: [ ],
	
	emptyAllFields: function(){
		for(i=0; i&lt;<span class="highlite">this</span>.formFields.length; i++){
			var elementID = <span class="highlite">this</span>.formFields[i];
			var field = document.getElementById(elementID);
			field.value = '';
		}
	}
};

//tell which form fields we want to work with
myHelper.formFields.push('txtName');
myHelper.formFields.push('txtEmail');
myHelper.formFields.push('txtAddress');

//clearing the text boxes:
myHelper.emptyAllFields();

var clearButton = document.getElementById('btnClear');
clearButton.onclick = myHelper.emptyAllFields;
			</pre>
						<p>
				So you think, nice, now I can click the Clear button on my page and those three text boxes 
				will be emptied. Then you try clicking the button only to get a runtime error. The error 
				will be related to (guess what?) the <span class="code">this</span> keyword. 
				The problem is that <span class="code">this.formFields</span> is not defined if 
				<span class="code">this</span> contains a reference to the button, which is 
				precisely what's happening. One quick solution would be to rewrite our last line of code.
			</p>
						<pre class="code">

clearButton.onclick = function(){ myHelper.emptyAllFields(); };
			</pre>
						<p>
				That way we create a brand new function that calls our helper method within the helper object's context.
			</p>
						<hr />
						<!-- Translators: please ignore and remove this next paragraph -->
						<h3>Books I've read and recommend</h3>
						<p>
				Some books are just too good not to pass the word forward. I haven't read a whole
				lot of Javascript books, but the following books were very helpful to me. They
				are very well written and didn't cause me to lose interest before reading half of it.
				I'm comfortable recommending them if you're on the market for a new book.
			</p>
						<p class="recommendations" id="books">
								<a href="http://www.amazon.com/exec/obidos/ASIN/0764579088/sergiopereira-20">
										<img border="0" src="images/0764579088.01._AA_SCTZZZZZZZ_.jpg" />
								</a>
								<img src="http://www.assoc-amazon.com/e/ir?t=sergiopereira-20&amp;l=as2&amp;o=1&amp;a=0764579088" class="tracker" />
								<a href="http://www.amazon.com/exec/obidos/ASIN/1932394613/sergiopereira-20">
										<img border="0" src="images/1932394613.01._AA_SCTZZZZZZZ_.jpg" />
								</a>
								<img src="http://www.assoc-amazon.com/e/ir?t=sergiopereira-20&amp;l=as2&amp;o=1&amp;a=1932394613" class="tracker" />
								<script type="text/javascript" src="http://www.assoc-amazon.com/s/link-enhancer?tag=sergiopereira-20">
								</script>
						</p>
						<noscript>
								<img src="http://www.assoc-amazon.com/s/noscript?tag=sergiopereira-20" alt="" />
						</noscript>
						<p class="footNote">
								<em>
					This article is not finished yet. If you find broken examples, 
					incorrect information, broken links, etc., please 
					<script><![CDATA[p('let me know')]]&gt;</script> and I'll try to fix it as soon as possible.
				</em>
						</p>
				</div>
		</body>
<img src ="http://www.blogjava.net/agen10120216/aggbug/102860.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/agen10120216/" target="_blank">今天不打cs</a> 2007-03-09 16:20 <a href="http://www.blogjava.net/agen10120216/archive/2007/03/09/102860.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>