ผลต่างระหว่างรุ่นของ "01219245/javascript1/tutorial3"

จาก Theory Wiki
ไปยังการนำทาง ไปยังการค้นหา
 
(ไม่แสดง 40 รุ่นระหว่างกลางโดยผู้ใช้คนเดียวกัน)
แถว 1: แถว 1:
In this tutorial we will learn about objects in JavaScript.  We will also develop a [https://en.wikipedia.org/wiki/Nim Nim game]. There are many versions of the game, we will try the version that is usually called the 21 game.
+
: ''This is part of [[01219245]]''
 +
 
 +
In this tutorial we will learn about objects in JavaScript.  We will also develop a [https://en.wikipedia.org/wiki/Nim Nim-type game]. There are many versions of the game, we will try the version that is usually called the 21 game.
  
 
In this game, there are 21 sticks.  There are two players: you and the computer.  Each player takes turn to take out the sticks.  The player can choose between 1 - 3 sticks.  The player that picks the last sticks wins.
 
In this game, there are 21 sticks.  There are two players: you and the computer.  Each player takes turn to take out the sticks.  The player can choose between 1 - 3 sticks.  The player that picks the last sticks wins.
แถว 8: แถว 10:
  
 
You may have known Object-Oriented Programming from other languages.  JavaScript's objects are rather different.  In languages like Java, C#, C++, objects is an instance of a class.  In JavaScript, you can have objects without having to think about classes.
 
You may have known Object-Oriented Programming from other languages.  JavaScript's objects are rather different.  In languages like Java, C#, C++, objects is an instance of a class.  In JavaScript, you can have objects without having to think about classes.
 +
 +
{{กล่องสี|#e0e0e0|
 +
'''Notes:''' In this tutorial we will only touch a small aspect of object-oriented programming in JavaScript, just barely enough to complete this program.  There is a lot of interesting concepts that we will revisit later on.}}
  
 
Objects in JavaScript is a bag that maps between keys and values.  Open a JavaScript console in your browser and try the following example.
 
Objects in JavaScript is a bag that maps between keys and values.  Open a JavaScript console in your browser and try the following example.
แถว 44: แถว 49:
  
 
This is useful when the property names are not valid identifier names.
 
This is useful when the property names are not valid identifier names.
 +
 +
You can also create an object with initial properties with the curly braces notation.
 +
 +
var cat = { name: 'meaw', age: 5 };  // --- output (don't type in) ---
 +
cat.name                              // 'meaw'
 +
cat.age                              // 5
  
 
=== Methods ===
 
=== Methods ===
แถว 59: แถว 70:
  
 
A property of an object which is a function is referred to as a '''method'''.
 
A property of an object which is a function is referred to as a '''method'''.
 +
 +
You can assign the same function to many objects.
 +
 +
function j() { console.log('up up up'); }
 +
dog.jump = j;
 +
cat.jumpjump = j;
 +
 +
When you call the method:
 +
 +
dog.jump()      // prints up up up
 +
cat.jumpjump()  // prints up up up
  
 
=== Accessing properties from a method: <tt>this</tt> ===
 
=== Accessing properties from a method: <tt>this</tt> ===
  
=== More than one objects of the same kind ===
+
A method that does not use any of the object's properties might not be very useful.  To access object's properties from a method, you use a keyword '''<tt>this</tt>'''.
 +
 
 +
: '''BEFORE YOU MOVE ON, LET ME SAY IT RIGHT AWAY THAT THE WAY <tt>this</tt> IN JAVASCRIPT WORKS IS DIFFERENT FROM THE WAY <tt>this</tt> IN JAVA, C#, OR C++ WORKS. SO BE CAREFUL.'''
 +
 
 +
Keyword <tt>this</tt> refers to the current object.  To see this, let's define function <tt>hello</tt> like this:
 +
 
 +
var hello = function() { alert( this.age ); };
 +
 
 +
This function is defined outside any class; and you can call it.
 +
 
 +
hello();        // you';l see an alert with undefined
 +
 
 +
Let's assign it to objects <tt>dog</tt> and <tt>cat</tt>.
 +
 
 +
dog.sayhi = hello;
 +
cat.morning = hello;
 +
 
 +
Let's call them.
  
== 21 Game ==
+
dog.sayhi();            // an alert with 10
 +
cat.morning();          // an alert with 5
 +
 
 +
With <tt>this</tt>, you can modify the object's properties.
 +
 
 +
cat.growup = function() { this.age++; }
 +
 
 +
This function increases the cat's age.
 +
 
 +
cat.growup();
 +
cat.growup();
 +
cat.morning();          // an alert with 7
 +
 
 +
=== Defining a complete object ===
 +
 
 +
When we actually use an object, we will not just define it as an empty object.  We usually define it with all the methods.  There are two typical ways.  We define object <tt>dog</tt> using object literal.
 +
 
 +
<syntaxhighlight lang="javascript">
 +
var dog = {
 +
    age: 10,
 +
    color: 'Black',
 +
   
 +
    bark: function() {
 +
        console.log( 'box box' );
 +
    },
 +
   
 +
    growup: function() {
 +
        this.age++;
 +
    },
 +
   
 +
    sayhi: function() {
 +
        alert( this.age );
 +
    }
 +
};
 +
</syntaxhighlight>
 +
 
 +
In this style, you have to be careful not to put comma (,) after the last method definition.
 +
 
 +
On the other hand, when we define object <tt>cat</tt>, we only specify data properties.  We then add methods later.
 +
 
 +
<syntaxhighlight lang="javascript">
 +
var cat = {
 +
    name: 'meaw',
 +
    age: 5
 +
};
 +
cat.jump = function() {
 +
    console.log( 'up up' );
 +
};
 +
cat.growup = function() {
 +
    this.age++;
 +
};
 +
cat.morning = function() {
 +
    alert( this.age );
 +
};
 +
</syntaxhighlight>
 +
 
 +
=== No classes? ===
 +
 
 +
In JavaScript, each object lives on its own.  It does not have to belong to a class.  An object-oriented programming languages with this capacity are usually called '''prototype-based''' object-oriented languages, while Java, C#, and C++ are called '''class-based''' object-oriented language.
 +
 
 +
What is a prototype?  Suppose that we need to have a lot of objects of the same kind, and if every object lives on its own, it will be rather hard to create a lot of them.  In prototype-based language, we usually create one object as a prototype and simply clone all objects that we need from the prototype. 
 +
 
 +
We will talk about this later on when we actually need it.  Right now, we will work on a project where each object is one-of-a-kind; so cloning is not our issue for now.
 +
 
 +
: If you are curious, you can read this [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model?redirectlocale=en-US&redirectslug=JavaScript%2FGuide%2FDetails_of_the_Object_Model guide].
 +
 
 +
== 21 Game -- Task breakdown ==
 +
Let's try to breakdown the tasks that we have to do to get our 21 game done.
 +
 
 +
Try to list a few tasks before looking at my take.
 +
 
 +
<div class="toccolours mw-collapsible mw-collapsed">
 +
See the task breakdown here.
 +
<div class="mw-collapsible-content">
 +
* Show the game screen with the current number of sticks.
 +
* Let the user take a number of sticks; update the number shown.
 +
* Make sure the user take the correct number of sticks (from 1 - 3).
 +
* Create a random computer player; let the player also take a number of sticks it its turn.
 +
* Make the computer player smarter.
 +
</div>
 +
</div>
  
 
== Picking sticks ==
 
== Picking sticks ==
 +
Let's start.  Create a directory for the project and create a Git repository there.
 +
 +
We will start with an empty page and script blocks that include jQuery.  This is our first version of <tt>index.html</tt>
 +
 +
<syntaxhighlight lang="html5">
 +
<!doctype html>
 +
<html lang="en">
 +
<body>
 +
 +
<script src="jquery.js"></script>
 +
<script type="text/javascript">
 +
</script>
 +
</body>
 +
</html>
 +
</syntaxhighlight>
 +
 +
Let's add some content to our page
 +
 +
<syntaxhighlight lang="html5">
 +
  <h1>Get the last one to win!</h1>
 +
 +
  Number of sticks: 21<br>
 +
 +
  <input><button>Pick</button>
 +
</syntaxhighlight>
 +
 +
Load the page in the browser to see if the page looks OK.
 +
 +
{{gitcomment|Create the first commit here.}}
 +
 +
If we look at the page, we need to assign id's to various element.  We also have create a span element to mark the current number of sticks (21).
 +
 +
<syntaxhighlight lang="html5">
 +
  Number of sticks: <span id="numSticks">21</span><br>
 +
 +
  <input id="pickNum"><button id="pickButton">Pick</button>
 +
</syntaxhighlight>
 +
 +
The HTML part of the page looks OK now.  Let's work on JavaScript.  We start by creating a variable for the number of sticks.  We also define an empty function to handle the click event of <tt>pickButton</tt>.
 +
 +
<syntaxhighlight lang="javascript">
 +
var numSticks = 21;
 +
 +
function pickSticks() {
 +
}
 +
 +
$(function(){
 +
    $("#pickButton").click(pickSticks);
 +
});
 +
</syntaxhighlight>
 +
 +
'''EXERCISE:''' Before proceeding on, try to implement function '''<tt>pickSticks</tt>''' that reads an integer from input <tt>pickNum</tt>, subtracts that from <tt>numSticks</tt>, and shows the updated <tt>numSticks</tt>.
  
== Using objects to encapsulate behavior ==
+
{{gitcomment|It's a good place to commit.}}
  
== Transcript ==
+
{{Callta|1. Show the program to the TA.}}
  
== Computer player ==
+
{{กล่องสี|#e0f0e0|
 +
:: ''When you are done with this exercise, [[01219245/javascript1/tutorial3/2|click here to proceed to the 2nd part of the tutorial]].''
 +
}}

รุ่นแก้ไขปัจจุบันเมื่อ 01:53, 9 กุมภาพันธ์ 2559

This is part of 01219245

In this tutorial we will learn about objects in JavaScript. We will also develop a Nim-type game. There are many versions of the game, we will try the version that is usually called the 21 game.

In this game, there are 21 sticks. There are two players: you and the computer. Each player takes turn to take out the sticks. The player can choose between 1 - 3 sticks. The player that picks the last sticks wins.

You can try it at [1].

Quick introduction to objects in JavaScript

You may have known Object-Oriented Programming from other languages. JavaScript's objects are rather different. In languages like Java, C#, C++, objects is an instance of a class. In JavaScript, you can have objects without having to think about classes.

Notes: In this tutorial we will only touch a small aspect of object-oriented programming in JavaScript, just barely enough to complete this program. There is a lot of interesting concepts that we will revisit later on.

Objects in JavaScript is a bag that maps between keys and values. Open a JavaScript console in your browser and try the following example.

We can use curly braces to enclose property names and values to define an object. To create an "empty" object, we write

var dog = {};

Variable dog now points to an object with no properties. Trying to accessing any of its property will give you undefined.

dog.age

We can assign a value to some property in the object with a standard assignment:

dog.age = 10;
dog.color = 'blue';

If you type

dog           

you'll see something like this:

Object { age=10, color="blue"}

Now you can type dog.age or dog.color to the console to read the object's properties.

You can also use another syntax for accessing properties, i.e., square bracket notation, like this:

dog['age']
dog["color"]

With this syntax, you use a string as an index to the object's properties. You can also assign a property with bracket notation:

dog['owner'] = 'John';

This is useful when the property names are not valid identifier names.

You can also create an object with initial properties with the curly braces notation.

var cat = { name: 'meaw', age: 5 };   // --- output (don't type in) ---
cat.name                              // 'meaw'
cat.age                               // 5

Methods

An object can also have functions for its properties. Let's add property bark:

dog.bark = function() { console.log('box box'); };

Try calling it. (How? Let's try both statements.)

dog.bark
dog.bark()

What do the above statements do?

A property of an object which is a function is referred to as a method.

You can assign the same function to many objects.

function j() { console.log('up up up'); }
dog.jump = j;
cat.jumpjump = j;

When you call the method:

dog.jump()       // prints up up up
cat.jumpjump()   // prints up up up

Accessing properties from a method: this

A method that does not use any of the object's properties might not be very useful. To access object's properties from a method, you use a keyword this.

BEFORE YOU MOVE ON, LET ME SAY IT RIGHT AWAY THAT THE WAY this IN JAVASCRIPT WORKS IS DIFFERENT FROM THE WAY this IN JAVA, C#, OR C++ WORKS. SO BE CAREFUL.

Keyword this refers to the current object. To see this, let's define function hello like this:

var hello = function() { alert( this.age ); };

This function is defined outside any class; and you can call it.

hello();         // you';l see an alert with undefined

Let's assign it to objects dog and cat.

dog.sayhi = hello;
cat.morning = hello;

Let's call them.

dog.sayhi();             // an alert with 10
cat.morning();           // an alert with 5

With this, you can modify the object's properties.

cat.growup = function() { this.age++; }

This function increases the cat's age.

cat.growup();
cat.growup();
cat.morning();          // an alert with 7

Defining a complete object

When we actually use an object, we will not just define it as an empty object. We usually define it with all the methods. There are two typical ways. We define object dog using object literal.

var dog = {
    age: 10,
    color: 'Black',
    
    bark: function() {
        console.log( 'box box' );
    },
    
    growup: function() {
        this.age++;
    },
    
    sayhi: function() {
        alert( this.age );
    }
};

In this style, you have to be careful not to put comma (,) after the last method definition.

On the other hand, when we define object cat, we only specify data properties. We then add methods later.

var cat = { 
    name: 'meaw', 
    age: 5 
};
cat.jump = function() {
    console.log( 'up up' );
};
cat.growup = function() {
    this.age++;
};
cat.morning = function() {
    alert( this.age );
};

No classes?

In JavaScript, each object lives on its own. It does not have to belong to a class. An object-oriented programming languages with this capacity are usually called prototype-based object-oriented languages, while Java, C#, and C++ are called class-based object-oriented language.

What is a prototype? Suppose that we need to have a lot of objects of the same kind, and if every object lives on its own, it will be rather hard to create a lot of them. In prototype-based language, we usually create one object as a prototype and simply clone all objects that we need from the prototype.

We will talk about this later on when we actually need it. Right now, we will work on a project where each object is one-of-a-kind; so cloning is not our issue for now.

If you are curious, you can read this guide.

21 Game -- Task breakdown

Let's try to breakdown the tasks that we have to do to get our 21 game done.

Try to list a few tasks before looking at my take.

See the task breakdown here.

  • Show the game screen with the current number of sticks.
  • Let the user take a number of sticks; update the number shown.
  • Make sure the user take the correct number of sticks (from 1 - 3).
  • Create a random computer player; let the player also take a number of sticks it its turn.
  • Make the computer player smarter.

Picking sticks

Let's start. Create a directory for the project and create a Git repository there.

We will start with an empty page and script blocks that include jQuery. This is our first version of index.html

<!doctype html>
<html lang="en">
<body>

<script src="jquery.js"></script>
<script type="text/javascript">
</script>
</body>
</html>

Let's add some content to our page

  <h1>Get the last one to win!</h1>

  Number of sticks: 21<br>

  <input><button>Pick</button>

Load the page in the browser to see if the page looks OK.

Gitmark.png Create the first commit here.

If we look at the page, we need to assign id's to various element. We also have create a span element to mark the current number of sticks (21).

  Number of sticks: <span id="numSticks">21</span><br>

  <input id="pickNum"><button id="pickButton">Pick</button>

The HTML part of the page looks OK now. Let's work on JavaScript. We start by creating a variable for the number of sticks. We also define an empty function to handle the click event of pickButton.

var numSticks = 21;

function pickSticks() {
}

$(function(){
    $("#pickButton").click(pickSticks);
});

EXERCISE: Before proceeding on, try to implement function pickSticks that reads an integer from input pickNum, subtracts that from numSticks, and shows the updated numSticks.

Gitmark.png It's a good place to commit.

Badge.png 1. Show the program to the TA.

When you are done with this exercise, click here to proceed to the 2nd part of the tutorial.