From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../javascript/building_blocks/events/index.html | 583 +++++++++++++++++++++ .../vi/learn/javascript/building_blocks/index.html | 59 +++ files/vi/learn/javascript/first_steps/index.html | 60 +++ .../learn/javascript/first_steps/math/index.html | 418 +++++++++++++++ .../javascript/first_steps/strings/index.html | 290 ++++++++++ .../first_steps/what_is_javascript/index.html | 422 +++++++++++++++ files/vi/learn/javascript/index.html | 82 +++ files/vi/learn/javascript/objects/index.html | 42 ++ .../javascript/objects/inheritance/index.html | 440 ++++++++++++++++ 9 files changed, 2396 insertions(+) create mode 100644 files/vi/learn/javascript/building_blocks/events/index.html create mode 100644 files/vi/learn/javascript/building_blocks/index.html create mode 100644 files/vi/learn/javascript/first_steps/index.html create mode 100644 files/vi/learn/javascript/first_steps/math/index.html create mode 100644 files/vi/learn/javascript/first_steps/strings/index.html create mode 100644 files/vi/learn/javascript/first_steps/what_is_javascript/index.html create mode 100644 files/vi/learn/javascript/index.html create mode 100644 files/vi/learn/javascript/objects/index.html create mode 100644 files/vi/learn/javascript/objects/inheritance/index.html (limited to 'files/vi/learn/javascript') diff --git a/files/vi/learn/javascript/building_blocks/events/index.html b/files/vi/learn/javascript/building_blocks/events/index.html new file mode 100644 index 0000000000..9fc6ba4253 --- /dev/null +++ b/files/vi/learn/javascript/building_blocks/events/index.html @@ -0,0 +1,583 @@ +--- +title: Giới thiệu về sự kiện +slug: Learn/JavaScript/Building_blocks/Events +tags: + - Article + - Beginner + - Event Handler + - JavaScript + - Learn + - events +translation_of: Learn/JavaScript/Building_blocks/Events +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}
+ +

Các sự kiện là các hành động hoặc sự cố xảy ra trong hệ thống mà bạn đang lập trình, hệ thống sẽ báo cho bạn biết về chúng để bạn có thể phản hồi lại theo cách nào đó nếu bạn muốn. Ví dụ: nếu người dùng nhấp vào một nút trên trang web, bạn có thể muốn phản hồi hành động đó bằng cách hiển thị một hộp thông tin. Trong bài viết này, chúng ta sẽ thảo luận về một số khái niệm quan trọng xung quanh các sự kiện và xem xét cách chúng hoạt động trong trình duyệt như thế nào. Đây không phải là một nghiên cứu đầy đủ mà chỉ là những gì bạn cần biết ở giai đoạn này.

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps.
Objective:To understand the fundamental theory of events, how they work in browsers, and how events may differ in different programming environments.
+ +

A series of fortunate events

+ +

As mentioned above, events are actions or occurrences that happen in the system you are programming — the system will fire a signal of some kind when an event occurs, and also provide a mechanism by which some kind of action can be automatically taken (e.g. some code running) when the event occurs. For example in an airport when the runway is clear for a plane to take off, a signal is communicated to the pilot, and as a result, they commence piloting the plane.

+ +

+ +

In the case of the Web, events are fired inside the browser window, and tend to be attached to a specific item that resides in it — this might be a single element, set of elements, the HTML document loaded in the current tab, or the entire browser window. There are a lot of different types of events that can occur, for example:

+ + + +

You will gather from this (and from glancing at the MDN Event reference) that there are a lot of events that can be responded to.

+ +

Each available event has an event handler, which is a block of code (usually a user-defined JavaScript function) that will be run when the event fires. When such a block of code is defined to be run in response to an event firing, we say we are registering an event handler. Note that event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening.

+ +
+

Note: It is important to note that web events are not part of the core JavaScript language — they are defined as part of the JavaScript APIs built into the browser.

+
+ +

A simple example

+ +

Let's look at a simple example to explain what we mean here. You've already seen events and event handlers used in many of the examples in this course already, but let's recap just to cement our knowledge. In the following example, we have a single {{htmlelement("button")}}, which when pressed, will make the background change to a random color:

+ +
<button>Change color</button>
+ + + +

The JavaScript looks like so:

+ +
var btn = document.querySelector('button');
+
+function random(number) {
+  return Math.floor(Math.random()*(number+1));
+}
+
+btn.onclick = function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

In this code, we store a reference to the button inside a variable called btn, using the {{domxref("Document.querySelector()")}} function. We also define a function that returns a random number. The third part of the code is the event handler. The btn variable points to a <button> element, and this type of object has a number of events that can fire on it, and therefore, event handlers are available. We are listening for the click event firing, by setting the onclick event handler property to equal an anonymous function containing code that generated a random RGB color and sets the <body> background-color equal to it.

+ +

This code will now be run whenever the click event fires on the <button> element, i.e., whenever a user clicks on it.

+ +

The example output is as follows:

+ +

{{ EmbedLiveSample('A_simple_example', '100%', 200, "", "", "hide-codepen-jsfiddle") }}

+ +

It's not just web pages

+ +

Another thing worth mentioning at this point is that events are not particular to JavaScript — most programming languages have some kind of event model, and the way it works will often differ from JavaScript's way. In fact, the event model in JavaScript for web pages differs from the event model for JavaScript as it is used in other environments.

+ +

For example, Node.js is a very popular JavaScript runtime that enables developers to use JavaScript to build network and server-side applications. The Node.js event model relies on listeners to listen for events and emitters to emit events periodically — it doesn't sound that different, but the code is quite different, making use of functions like on() to register an event listener, and once() to register an event listener that unregisters after it has run once. The HTTP connect event docs provide a good example of use.

+ +

As another example, you can now also use JavaScript to build cross-browser add-ons — browser functionality enhancements — using a technology called WebExtensions. The event model is similar to the web events model, but a bit different — event listeners properties are camel-cased (e.g. onMessage rather than onmessage), and need to be combined with the addListener function. See the runtime.onMessage page for an example.

+ +

You don't need to understand anything about other such environments at this stage in your learning; we just wanted to make it clear that events can differ in different programming environments.

+ +

Ways of using web events

+ +

There are a number of different ways in which you can add event listener code to web pages so that it will be run when the associated event fires. In this section, we will review the different mechanisms and discuss which ones you should use.

+ +

Event handler properties

+ +

These are the properties that exist to contain event handler code that we have seen most frequently during the course. Returning to the above example:

+ +
var btn = document.querySelector('button');
+
+btn.onclick = function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

The onclick property is the event handler property being used in this situation. It is essentially a property like any other available on the button (e.g. btn.textContent, or btn.style), but it is a special type — when you set it to be equal to some code, that code will be run when the event fires on the button.

+ +

You could also set the handler property to be equal to a named function name (like we saw in Build your own function). The following would work just the same:

+ +
var btn = document.querySelector('button');
+
+function bgChange() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.onclick = bgChange;
+ +

There are many different event handler properties available. Let's do an experiment.

+ +

First of all, make a local copy of random-color-eventhandlerproperty.html, and open it in your browser. It's just a copy of the simple random color example we've been playing with already in this article. Now try changing btn.onclick to the following different values in turn, and observing the results in the example:

+ + + +

Some events are very general and available nearly anywhere (for example an onclick handler can be registered on nearly any element), whereas some are more specific and only useful in certain situations (for example it makes sense to use onplay only on specific elements, such as {{htmlelement("video")}}).

+ +

Inline event handlers — don't use these

+ +

You might also see a pattern like this in your code:

+ +
<button onclick="bgChange()">Press me</button>
+
+ +
function bgChange() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

The earliest method of registering event handlers found on the Web involved event handler HTML attributes (aka inline event handlers) like the one shown above — the attribute value is literally the JavaScript code you want to run when the event occurs. The above example invokes a function defined inside a {{htmlelement("script")}} element on the same page, but you could also insert JavaScript directly inside the attribute, for example:

+ +
<button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button>
+ +

You'll find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are just doing something really quick, but they very quickly become unmanageable and inefficient.

+ +

For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse — keeping your JavaScript all in one place is better; if it is in a separate file you can apply it to multiple HTML documents.

+ +

Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would very quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:

+ +
var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i < buttons.length; i++) {
+  buttons[i].onclick = bgChange;
+}
+ +
+

Note: Separating your programming logic from your content also makes your site more friendly to search engines.

+
+ +

addEventListener() and removeEventListener()

+ +

The newest type of event mechanism is defined in the Document Object Model (DOM) Level 2 Events Specification, which provides browsers with a new function — addEventListener(). This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this:

+ +
var btn = document.querySelector('button');
+
+function bgChange() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

Inside the addEventListener() function, we specify two parameters — the name of the event we want to register this handler for, and the code that comprises the handler function we want to run in response to it. Note that it is perfectly appropriate to put all the code inside the addEventListener() function, in an anonymous function, like this:

+ +
btn.addEventListener('click', function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+});
+ +

This mechanism has some advantages over the older mechanisms discussed earlier. For a start, there is a counterpart function, removeEventListener(), which removes a previously added listener. For example, this would remove the listener set in the first code block in this section:

+ +
btn.removeEventListener('click', bgChange);
+ +

This isn't significant for simple, small programs, but for larger, more complex programs it can improve efficiency to clean up old unused event handlers. Plus, for example, this allows you to have the same button performing different actions in different circumstances — all you've got to do is add/remove event handlers as appropriate.

+ +

Second, you can also register multiple handlers for the same listener. The following two handlers would not be applied:

+ +
myElement.onclick = functionA;
+myElement.onclick = functionB;
+ +

As the second line would overwrite the value of onclick set by the first. This would work, however:

+ +
myElement.addEventListener('click', functionA);
+myElement.addEventListener('click', functionB);
+ +

Both functions would now run when the element is clicked.

+ +

In addition, there are a number of other powerful features and options available with this event mechanism. These are a little out of scope for this article, but if you want to read up on them, have a look at the addEventListener() and removeEventListener() reference pages.

+ +

What mechanism should I use?

+ +

Of the three mechanisms, you definitely shouldn't use the HTML event handler attributes — these are outdated, and bad practice, as mentioned above.

+ +

The other two are relatively interchangeable, at least for simple uses:

+ + + +

The main advantages of the third mechanism are that you can remove event handler code if needed, using removeEventListener(), and you can add multiple listeners of the same type to elements if required. For example, you can call addEventListener('click', function() { ... }) on an element multiple times, with different functions specified in the second argument. This is impossible with event handler properties because any subsequent attempts to set a property will overwrite earlier ones, e.g.:

+ +
element.onclick = function1;
+element.onclick = function2;
+etc.
+ +
+

Note: If you are called upon to support browsers older than Internet Explorer 8 in your work, you may run into difficulties, as such ancient browsers use different event models from newer browsers. But never fear, most JavaScript libraries (for example jQuery) have built-in functions that abstract away cross-browser differences. Don't worry about this too much at this stage in your learning journey.

+
+ +

Other event concepts

+ +

In this section, we will briefly cover some advanced concepts that are relevant to events. It is not important to understand these fully at this point, but it might serve to explain some code patterns you'll likely come across from time to time.

+ +

Event objects

+ +

Sometimes inside an event handler function, you might see a parameter specified with a name such as event, evt, or simply e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example again slightly:

+ +
function bgChange(e) {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  e.target.style.backgroundColor = rndCol;
+  console.log(e);
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

Here you can see that we are including an event object, e, in the function, and in the function setting a background color style on e.target — which is the button itself. The target property of the event object is always a reference to the element that the event has just occurred upon. So in this example, we are setting a random background color on the button, not the page.

+ +
+

Note: You can use any name you like for the event object — you just need to choose a name that you can then use to reference it inside the event handler function. e/evt/event are most commonly used by developers because they are short and easy to remember. It's always good to stick to a standard.

+
+ +

e.target is incredibly useful when you want to set the same event handler on multiple elements and do something to all of them when an event occurs on them. You might, for example, have a set of 16 tiles that disappear when they are clicked on. It is useful to always be able to just set the thing to disappear as e.target, rather than having to select it in some more difficult way. In the following example (see useful-eventtarget.html for the full source code; also see it running live here), we create 16 {{htmlelement("div")}} elements using JavaScript. We then select all of them using {{domxref("document.querySelectorAll()")}}, then loop through each one, adding an onclick handler to each that makes it so that a random color is applied to each one when clicked:

+ +
var divs = document.querySelectorAll('div');
+
+for (var i = 0; i < divs.length; i++) {
+  divs[i].onclick = function(e) {
+    e.target.style.backgroundColor = bgChange();
+  }
+}
+ +

The output is as follows (try clicking around on it — have fun):

+ + + +

{{ EmbedLiveSample('Hidden_example', '100%', 400, "", "", "hide-codepen-jsfiddle") }}

+ +

Most event handlers you'll encounter just have a standard set of properties and functions (methods) available on the event object (see the {{domxref("Event")}} object reference for a full list). Some more advanced handlers, however, add specialist properties containing extra data that they need to function. The Media Recorder API, for example, has a dataavailable event, which fires when some audio or video has been recorded and is available for doing something with (for example saving it, or playing it back). The corresponding ondataavailable handler's event object has a data property available containing the recorded audio or video data to allow you to access it and do something with it.

+ +

Preventing default behavior

+ +

Sometimes, you'll come across a situation where you want to stop an event doing what it does by default. The most common example is that of a web form, for example, a custom registration form. When you fill in the details and press the submit button, the natural behaviour is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified.)

+ +

The trouble comes when the user has not submitted the data correctly — as a developer, you'll want to stop the submission to the server and give them an error message telling them what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. Let's look at a simple example.

+ +

First, a simple HTML form that requires you to enter your first and last name:

+ +
<form>
+  <div>
+    <label for="fname">First name: </label>
+    <input id="fname" type="text">
+  </div>
+  <div>
+    <label for="lname">Last name: </label>
+    <input id="lname" type="text">
+  </div>
+  <div>
+     <input id="submit" type="submit">
+  </div>
+</form>
+<p></p>
+ + + +

Now some JavaScript — here we implement a very simple check inside an onsubmit event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. If they are, we call the preventDefault() function on the event object — which stops the form submission — and then display an error message in the paragraph below our form to tell the user what's wrong:

+ +
var form = document.querySelector('form');
+var fname = document.getElementById('fname');
+var lname = document.getElementById('lname');
+var submit = document.getElementById('submit');
+var para = document.querySelector('p');
+
+form.onsubmit = function(e) {
+  if (fname.value === '' || lname.value === '') {
+    e.preventDefault();
+    para.textContent = 'You need to fill in both names!';
+  }
+}
+ +

Obviously, this is pretty weak form validation — it wouldn't stop the user validating the form with spaces or numbers entered into the fields, for example — but it is ok for example purposes. The output is as follows:

+ +

{{ EmbedLiveSample('Preventing_default_behavior', '100%', 140, "", "", "hide-codepen-jsfiddle") }}

+ +
+

Note: for the full source code, see preventdefault-validation.html (also see it running live here.)

+
+ +

Event bubbling and capture

+ +

The final subject to cover here is something that you'll not come across often, but it can be a real pain if you don't understand it. Event bubbling and capture are two mechanisms that describe what happens when two handlers of the same event type are activated on one element. Let's look at an example to make this easier — open up the show-video-box.html example in a new tab (and the source code in another tab.) It is also available live below:

+ + + +

{{ EmbedLiveSample('Hidden_video_example', '100%', 500, "", "", "hide-codepen-jsfiddle") }}

+ +

This is a pretty simple example that shows and hides a {{htmlelement("div")}} with a {{htmlelement("video")}} element inside it:

+ +
<button>Display video</button>
+
+<div class="hidden">
+  <video>
+    <source src="rabbit320.mp4" type="video/mp4">
+    <source src="rabbit320.webm" type="video/webm">
+    <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+  </video>
+</div>
+ +

When the {{htmlelement("button")}} is clicked, the video is displayed, by changing the class attribute on the <div> from hidden to showing (the example's CSS contains these two classes, which position the box off the screen and on the screen, respectively):

+ +
btn.onclick = function() {
+  videoBox.setAttribute('class', 'showing');
+}
+ +

We then add a couple more onclick event handlers — the first one to the <div> and the second one to the <video>. The idea is that when the area of the <div> outside the video is clicked, the box should be hidden again; when the video itself is clicked, the video should start to play.

+ +
videoBox.onclick = function() {
+  videoBox.setAttribute('class', 'hidden');
+};
+
+video.onclick = function() {
+  video.play();
+};
+ +

But there's a problem — currently, when you click the video it starts to play, but it causes the <div> to also be hidden at the same time. This is because the video is inside the <div> — it is part of it — so clicking on the video actually runs both the above event handlers.

+ +

Bubbling and capturing explained

+ +

When an event is fired on an element that has parent elements (e.g. the {{htmlelement("video")}} in our case), modern browsers run two different phases — the capturing phase and the bubbling phase.

+ +

In the capturing phase:

+ + + +

In the bubbling phase, the exact opposite occurs:

+ + + +

+ +

(Click on image for bigger diagram)

+ +

In modern browsers, by default, all event handlers are registered in the bubbling phase. So in our current example, when you click the video, the click event bubbles from the <video> element outwards to the <html> element. Along the way:

+ + + +

Fixing the problem with stopPropagation()

+ +

This is annoying behavior, but there is a way to fix it! The standard event object has a function available on it called stopPropagation(), which when invoked on a handler's event object makes it so that handler is run, but the event doesn't bubble any further up the chain, so no more handlers will be run.

+ +

We can, therefore, fix our current problem by changing the second handler function in the previous code block to this:

+ +
video.onclick = function(e) {
+  e.stopPropagation();
+  video.play();
+};
+ +

You can try making a local copy of the show-video-box.html source code and having a go at fixing it yourself, or looking at the fixed result in show-video-box-fixed.html (also see the source code here).

+ +
+

Note: Why bother with both capturing and bubbling? Well, in the bad old days when browsers were much less cross-compatible than they are now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is the one modern browsers implemented.

+
+ +
+

Note: As mentioned above, by default all event handlers are registered in the bubbling phase, and this makes more sense most of the time. If you really want to register an event in the capturing phase instead, you can do so by registering your handler using addEventListener(), and setting the optional third property to true.

+
+ +

Event delegation

+ +

Bubbling also allows us to take advantage of event delegation — this concept relies on the fact that if you want some code to run when you click on any one of a large number of child elements, you can set the event listener on their parent and have events that happen on them bubble up to their parent, rather than having to set the event listener on every child individually.

+ +

A good example is a series of list items — if you want each one of them to pop up a message when clicked, you can set the click event listener on the parent <ul>, and it will bubble to the list items.

+ +

This concept is explained further on David Walsh's blog, with multiple examples — see How JavaScript Event Delegation Works.

+ +

Conclusion

+ +

You should now know all you need to know about web events at this early stage. As mentioned above, events are not really part of the core JavaScript — they are defined in browser Web APIs.

+ +

Also, it is important to understand that the different contexts in which JavaScript is used tend to have different event models — from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript). We are not expecting you to understand all these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development.

+ +

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/vi/learn/javascript/building_blocks/index.html b/files/vi/learn/javascript/building_blocks/index.html new file mode 100644 index 0000000000..097d323722 --- /dev/null +++ b/files/vi/learn/javascript/building_blocks/index.html @@ -0,0 +1,59 @@ +--- +title: Nền tảng của JavaScript +slug: Learn/JavaScript/Building_blocks +tags: + - Article + - Assessment + - Beginner + - CodingScripting + - Conditionals + - Functions + - Guide + - Introduction + - JavaScript + - Landing + - Loops + - Module + - NeedsTranslation + - TopicStub + - events + - 'l10n:priority' +translation_of: Learn/JavaScript/Building_blocks +--- +
{{LearnSidebar}}
+ +

Trong mô-đun này, chúng ta tiếp tục công việc tìm hiểu tất cả các tính năng cơ bản nhất của JavaScript, và chuyển sự chú ý sang các khối mã thường gặp như câu lệnh điều kiện, vòng lặp, hàm và sự kiện. Trong khóa học, bạn đã thấy những thứ này trước đây, nhưng chỉ lướt qua - giờ đây chúng ta sẽ thảo luận chúng một cách rõ ràng.

+ +

Prerequisites

+ +

Before starting this module, you should have some familiarity with the basics of HTML and CSS, and you should have also worked through our previous module, JavaScript first steps.

+ +
+

Note: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Thimble.

+
+ +

Guides

+ +
+
Making decisions in your code — conditionals
+
In any programming language, code needs to make decisions and carry out actions accordingly depending on different inputs. For example, in a game, if the player's number of lives is 0, then it's game over. In a weather app, if it is being looked at in the morning, show a sunrise graphic; show stars and a moon if it is nighttime. In this article we'll explore how conditional structures work in JavaScript.
+
Looping code
+
Sometimes you need a task done more than once in a row. For example, looking through a list of names. In programming, loops perform this job very well. Here we will look at loop structures in JavaScript.
+
Functions — reusable blocks of code
+
Another essential concept in coding is functions. Functions allow you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command — rather than having to type out the same code multiple times. In this article we'll explore fundamental concepts behind functions such as basic syntax, how to invoke and define functions, scope, and parameters.
+
Build your own function
+
With most of the essential theory dealt with previously, this article provides a practical experience. Here you'll get some practice with building up your own custom function. Along the way, we'll also explain some further useful details of dealing with functions.
+
Function return values
+
The last essential concept you must know about a function is return values. Some functions don't return a significant value after completion, but others do. It's important to understand what their values are, how to make use of them in your code, and how to make your own custom functions return useful values. 
+
Introduction to events
+
Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. For example if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box. In this final article we will discuss some important concepts surrounding events, and look at how they work in browsers.
+
+ +

Assessments

+ +

The following assessment will test your understanding of the JavaScript basics covered in the guides above.

+ +
+
Image gallery
+
Now that we've looked at the fundamental building blocks of JavaScript, we'll test your knowledge of loops, functions, conditionals and events by building a fairly common item you'll see on a lot of websites — a JavaScript-powered image gallery.
+
diff --git a/files/vi/learn/javascript/first_steps/index.html b/files/vi/learn/javascript/first_steps/index.html new file mode 100644 index 0000000000..57fe422862 --- /dev/null +++ b/files/vi/learn/javascript/first_steps/index.html @@ -0,0 +1,60 @@ +--- +title: JavaScript cơ bản +slug: Learn/JavaScript/First_steps +tags: + - Biến + - Chuỗi + - Cơ Bản + - Hướng dẫn + - JavaScript + - Mảng + - Toán tử +translation_of: Learn/JavaScript/First_steps +--- +
{{LearnSidebar}}
+ +

Trong mô-đun (module) đầu tiên về JavaScript, đầu tiên chúng ta sẽ trả lời một vài câu hỏi căn bản chẳng hạn "JavaScript là gì?", "nó trông như thế nào?", và "nó có thể làm gì?", trước khi chuyển bạn sang trải nghiệm thực hành đầu tiên bằng việc viết JavaScript. Sau đó, chúng ta sẽ thảo luận chi tiết một vài cấu phần chính, chẳng hạn như các biến (variables), các chuỗi (strings), các số (numbers) và các mảng (arrays).

+ +

Điều Kiện Tiên Quyết

+ +

Trước khi bắt đầu mô-đun này, bạn không cần phải biết trước bất kì kiến thức JavaScript nào, nhưng cần một chút hiểu biết về HTML và CSS. Lời khuyên là bạn nên tìm hiểu các mô-đun sau trước khi bắt đầu với JavaScript:

+ + + +
+

Note: Nếu bạn đang thực hành trên một máy tính/máy tính bảng/ hoặc các thiết bị mà bạn không có quyền tạo các files, bạn có thể thực hành các ví dụ trong bài học trên trình biên tập code online như JSBin or Thimble.

+
+ +

Chuỗi Bài Hướng Dẫn

+ +
+
What is JavaScript?
+
Chào mừng đến khóa học JavaScript cơ bản của MDN! Trong bài đầu tiên chúng ta sẽ nhìn nhận JavaScript từ góc độ tổng quát, trả lời các câu hỏi như "JavaScript là gì?" và "nó có khả năng gì?" cũng như giúp bạn làm quen với các chức năng của JavaScript.
+
A first splash into JavaScript
+
Giờ bạn đã được học lý thuyết tổng quát về JavaScript cũng như khả năng ứng dụng của chúng. Tiếp theo chúng ta sẽ tiềm hiểu nhanh những tính năng cơ bản trong JavaScript thông qua thực hành, trong bài này, bạn sẽ được hướng dẫn từng bước xây dựng trò chơi "Đoán số" đơn giản.
+
What went wrong? Troubleshooting JavaScript
+
Trò chơi "Đoán số" trong bài trước mà bạn đã xây dựng, khả năng cao là chương trình của bạn không hoạt động như mong muốn. Đừng sợ - bài này sẽ giúp bạn không phải "vò đầu bức tai" trong những trường hợp như vậy bằng một vài mẹo đơn giản - tìm và chữa lỗi chương trình JavaScript.
+
Storing the information you need — Variables
+
Trong những bài trước bạn được tìm hiểu JavaScript là gì, khả năng ứng dụng của nó và cách kết hợp nó với các công nghệ web khác cũng như các tính năng cốt lõi nhìn từ góc độ tổng quát. Trong bài này chúng ta sẽ bắt đầu làm việc với thành phần cơ bản nhất của JavaScript - "Các Biến".
+
Basic math in JavaScript — numbers and operators
+
Tiếp theo trong khóa học chúng ta sẽ thảo luận về toán học trong JavaScript - cách kết hợp các toán tử, toán hạng và các tính năng khác để vận dụng chúng một cách thành công.
+
Handling text — strings in JavaScript
+
Trong phần này chúng ta sẽ tìm hiểu về chuỗi (string) - tên gọi của các đoạn văn bản trong lập trình. Bài này tập trung vào những hiểu biết chung về chuỗi mà bạn thật sự cần phải biết khi học JavaScript như tạo chuỗi, escape quote trong chuỗi, xâu các chuỗi và kí tự cùng nhau.
+
Useful string methods
+
Giờ chúng ta đã tìm hiểu cơ bản về chuỗi, hãy tiến thêm một bước nữa và bắt đầu nghĩ về những cách vận dụng hữu ích nào chúng ta có thể thực hiện trên chuỗi với các phương thức (methods) dựng sẵn như tìm độ dài (length) của chuỗi, xâu (join) và phân tách (split) chuỗi, tách kí tự từ một chuỗi vv...
+
Arrays
+
Trong bài cuối của mô-đun này, chúng ta sẽ được giới thiệu về mảng (arrays) - một cách tiện lợi để lưu trữ danh sách các phần tử của một dãy thông tin trong một tên biến duy nhất. Tìm hiểu tính hữu dụng của kiểu dữ liệu mảng, khám phá cách tạo mảng, nhận, thêm, xóa phần tử được lưu trữ trong mảng vv...
+
+ +

Bài Tập

+ +

Bài tập sau đây sẽ giúp bạn kiểm tra kiến thức JavaScript cơ bản được trình bày trong mô-đun.

+ +
+
Silly story generator
+
Trong bài tập này bạn sẽ ứng dụng những kiến thức trong mô-đun để tạo một ứng dụng thú vị. Ứng dụng của bạn có nhiệm vụ tạo ra những câu chuyện ngớ ngẩn một cách ngẫu nhiên. Chúc vui!
+
diff --git a/files/vi/learn/javascript/first_steps/math/index.html b/files/vi/learn/javascript/first_steps/math/index.html new file mode 100644 index 0000000000..d4a9085d82 --- /dev/null +++ b/files/vi/learn/javascript/first_steps/math/index.html @@ -0,0 +1,418 @@ +--- +title: Toán học cơ bản trong JavaScript — số và toán tử +slug: Learn/JavaScript/First_steps/Math +translation_of: Learn/JavaScript/First_steps/Math +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps")}}
+ +

Tới đây ta sẽ bàn về toán học trong JavaScript — cách sử dụng {{Glossary("Operator","toán tử")}} và các tính năng khác để thao tác thành công với các con số phục vụ mục đích của chúng ta.

+ + + + + + + + + + + + +
Điều kiện tiên quyết:Biết cách sử dụng máy tính cơ bản, hiểu cơ bản về HTML và CSS, hiểu được JavaScript là gì.
Mục tiêu:Quen với cơ bản của toán trong JavaScript.
+ +

Tất cả mọi người đều yêu toán

+ +

Được rồi, có thể là không. Một số trong chúng ta yêu toán, một số thì ghét toán ngay từ khi ta phải học bảng cửu chương và cách chia số lớn ở trường, và một số khác thì đứng ở đâu đó giữa cả hai. Nhưng ta chẳng thể phủ nhận rằng toán là một phần cốt lõi của cuộc sống mà ta không thể nào tiến xa nếu không có nó. Đặc biệt là khi ta ta học cách lập trình JavaScript (hoặc bất kì ngôn ngữ lập trình nào khác) - chủ yếu phụ thuộc vào xử lý dữ liệu kiểu số, tính toán giá trị mới, vân vân... khiến bạn không khỏi bất ngờ khi nhận ra JavaScript có sẵn đầy đủ các hàm toán học.

+ +

Bài viết này chỉ đề cập tới những phần cơ bản mà bạn cần phải biết vào lúc này.

+ +

Kiểu số học

+ +

Trong lập trình, thậm chí cả hệ số thập phân xoàng mà ta đều hiểu rõ cũng phức tạp hơn bạn có thể mường tượng được. Chúng tôi dùng nhiều thuật ngữ khác nhau để mô tả các kiểu số thập phân khác nhau, chẳng hạn:

+ + + +

Chúng tôi còn có một số kiểu hệ số khác! Thập phần là hệ cơ số 10 (tức là sử dụng 0–9 trong từng hàng từ đơn vị đến chục trăm...), nhưng chúng tôi cũng có những thứ như là:

+ + + +

Trước khi nghĩ rằng não bạn sắp tan chảy, dừng lại ngay đó! Để bắt đầu, ta sẽ chỉ dùng số thập phân xuyên suốt khoá học này; hiếm khi bạn phải nghĩ đến dạng số khác, nếu điều đó xảy ra.

+ +

Tin mừng thứ hai là không giống như một số ngôn ngữ lập trình khác, JavaScript chỉ có duy nhất một kiểu dữ liệu cho số, đó là, {{jsxref("Number")}}. Điều này nghĩa là dù bạn gặp phải kiểu số học nào trong JavaScript, bạn cũng có thể xử lý chúng cùng một cách.

+ +

Với tôi tất cả chỉ là số

+ +

Hãy thử chơi với một vài con số để làm quen với cú pháp căn bản mà ta cần nào. Nhập lệnh được liệt kê bên dưới vào JavaScript console trong công cụ dành cho nhà phát triển của bạn, hoặc dùng console dựng sẵn phía dưới tuỳ thích.

+ +

{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/variables/index.html", '100%', 300)}}

+ +

Mở trong cửa sổ mới

+ +
    +
  1. Trước hết, hay khai báo một cặp biến và khởi tạo lần lượt giá trị cho chúng với integer (số nguyên) và float (số thực), rồi gõ tên từng biến vào để kiểm tra thứ tự của chúng: +
    var myInt = 5;
    +var myFloat = 6.667;
    +myInt;
    +myFloat;
    +
  2. +
  3. Giá trị số học không cần tới cặp dấu nháy — thử khai báo và khởi tạo thêm vài cặp biến nữa trước khi chuyển sang bước tiếp theo.
  4. +
  5. Giờ hãy kiểm tra xem hai biến vừa tạo của chúng ta có cùng kiểu dữ liệu không. Có một toán tử trong JavaScript tên là {{jsxref("Operators/typeof", "typeof")}} làm được điều này. Hãy nhập hai dòng phía dưới: +
    typeof myInt;
    +typeof myFloat;
    + Giá trị trả về sẽ luôn là "number" trong cả hai trường hợp — điều này khiến mọi thứ dễ dàng hơn thay vì có nhiều kiểu dữ liệu khác nhau, và ta sẽ phải xử lý theo các cách khác nhau. Phù!
  6. +
+ +

Toán tử số học

+ +

Toán tử số học là những toán tử căn bản để ta dùng cho phép tính:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Toán tửTênMục đíchVí dụ
+CộngCộng hai số lại với nhau.6 + 9
-TrừTrừ số bên trái bằng số bên phải.20 - 15
*NhânNhân hai số lại với nhau.3 * 7
/ChiaChia số bên trái bằng số bên phải.10 / 5
%Chia lấy dư (thi thoảng gọi là modulo) +

Trả về phần dư sau khi bạn thực hiện phép chia số bên trái cho số bên phải.

+
8 % 3 (trả về 2, bởi vì 3 nhân 2 được 6, 8 trừ 6 còn 2.)
+ +
+

Ghi chú: Đôi khi bạn sẽ thấy các số trong phép tính được đề cập dưới dạng các {{Glossary("Operand", "toán hạng")}}.

+
+ +

Chắc chắn chúng tôi không cần dạy bạn cách làm toán căn bản, nhưng chúng tôi muốn thử độ hiểu về cú pháp liên quan. Hãy thử nhập ví dụ bên dưới vào trong JavaScript console trong công cụ dành cho nhà phát triển của bạn, hoặc dùng console dựng sẵn phía dưới tuỳ thích, để bạn quen với cú pháp.

+ +
    +
  1. Trước hết hãy thử tự nhập vào vài ví dụ đơn giản, như là +
    10 + 7
    +9 * 8
    +60 % 3
    +
  2. +
  3. Bạn còn có thể thử khai báo và khởi tạo vài số bên trong biến, vả thử dùng các biến này trong phép tính — các biến sẽ hành xử như giá trị chúng đang mang. Chẳng hạn: +
    var num1 = 10;
    +var num2 = 50;
    +9 * num1;
    +num2 / num1;
    +
  4. +
  5. Cuối phần này, hãy thử nhập vài biểu thức phức tạp hơn một chút, như là: +
    5 + 10 * 3;
    +num2 % 9 * num1;
    +num2 + num1 / 8 + 2;
    +
  6. +
+ +

Một vài phép tính phía trên không trả về giá trị mà bạn mong muốn; phần dưới đây sẽ giải thích cho bạn lý do.

+ +

Thứ tự ưu tiên toán tử

+ +

Hãy xem lại ví dụ cuối cùng phía trên, giả sử num2 giữ giá trị là 50 và num1 giữ giá trị là 10 (như đã khởi tạo ở phía trên):

+ +
num2 + num1 / 8 + 2;
+ +

Là con người, có lẽ bạn sẽ đọc là "50 cộng 10 bằng 60", rồi "8 cộng 2 bằng 10", và cuối cùng "60 chia cho 10 bằng 6".

+ +

Nhưng trình duyệt thực hiện từ "10 chia cho 8 bằng 1.25", rồi "50 cộng 1.25 cộng 2 bằng 53.25".

+ +

Đó là bởi vì thứ tự ưu tiên toán tử — vài toán tử sẽ được áp dụng trước toán tử khác trong khi tính toán kết quả của một phép tính (hay còn gọi là biển thức, trong lập trình). Thứ tự ưu tiên toán tử trong JavaScript giống hệt với những gì ta được dạy ở trường — Nhân và chia luôn được thực hiện trước, rồi tới cộng và trừ (phép tính luôn thực hiện từ trái qua phải).

+ +

Nếu bạn muốn vượt thứ tự ưu tiên toán tử, bạn có thể đặt cặp ngoặc tròn quanh phần mà bạn muốn thực hiện trước. Thế nên để trả về giá trị 6, ta sẽ làm như sau:

+ +
(num2 + num1) / (8 + 2);
+ +

Hãy thử xem.

+ +
+

Ghi chú: Danh sách tất cả toán tử và thứ tự của chúng trong JavaScript có thể được tìm thấy trong Biểu thức và toán tử.

+
+ +

Toán tử tăng và giảm

+ +

Đôi khi bạn sẽ muốn cộng hoặc trừ liên tục thêm/ bớt một với một biến số học nhất định. Việc này có thể dễ dàng thực hiện bằng toán tử tăng (++) và toán tử giảm (--). Chúng tôi đã dùng ++ trong trò chơi "Đoán số" trong bài viết first splash into JavaScript của chúng tôi, khi chúng tôi thêm 1 vào biến guessCount để đếm số lần đáon của người dùng sau mỗi lượt.

+ +
guessCount++;
+ +
+

Ghi chú: Chúng được dùng phần lớn trong vòng lặp, ta sẽ học về nó trong các bài tiếp trong khoá học này. Chẳng hạn, bạn muốn lặp qua danh sách các đơn giá, và thêm thuế giá trị gia tăng vào mỗi đơn giá. Bạn có thể lặp qua từng giá trị rồi đồng thời tính toán thuế và thêm vào đơn giá. Biến tăng sẽ được dùng để chuyển sang giá trị kế tiếp khi cần. Chúng tôi đã chuẩn bị sẵn một ví dụ đơn giản để cho bạn xem cách hoạt động của nó — thử nó ngay đi, và trông vào mã nguồn này để xem liệu bạn có thể tìm thấy biến tăng hay không! Ta sẽ xem chi tiết về vòng lặp trong các bài viết tiếp theo.

+
+ +

Hãy thử những dòng lệnh dưới đây trong console của bạn. Trước khi bắt đầu, hãy nhớ rằng bạn không thể áp dụng những toán tử vừa kể trên trực tiếp vào số, nghe có vẻ hơi lạ nhỉ, nhưng ta chỉ có thể gán giá trị mới cập nhật vào một biến, chứ không thể thực thi trên chính giá trị đó. Làm như sau sẽ hiện ra lỗi:

+ +
3++;
+ +

Thế nên, bạn chỉ có thể dùng toán tử tăng với biến đã tồn tại. Thử lệnh này xem:

+ +
var num1 = 4;
+num1++;
+ +

Được rồi, kì quái tập 2! Khi làm theo bạn sẽ thấy giá trị trả về là 4 — đó là bởi vì trình duyệt trả về giá trị hiện tại, rồi tăng giá trị của biến lên. Bạn sẽ thấy giá trị của biến đã tăng lên nếu nhập lại biến vào console:

+ +
num1;
+ +

Điều tương tự xảy ra với --, hãy thử đoạn bên dưới:

+ +
var num2 = 6;
+num2--;
+num2;
+ +
+

Ghi chú: Bạn có thể bắt trình duyệt làm điều ngược lại — tăng giảm giá trị của biến rồi trả về giá trị — bằng cách đặt toán tử lên phía trước biến thay vì đặt ở sau. Thử lại ví dụ trên một lần nữa, nhưng lần này hãy dùng ++num1--num2.

+
+ +

Toán tử gán

+ +

Toán tử gán là những toán tử gán giá trị cho biến. Ta đã dùng toán tử đơn giản nhất, =, rất nhiều lần — nó đơn thuần gán giá trị bên phải cho biến bên trái:

+ +
var x = 3; // x giữ giá trị 3
+var y = 4; // y giữ giá trị 4
+x = y; // x giờ giữ giá trị giống hệt với y, 4
+ +

Nhưng có vài kiểu phức tạp hơn, tạo ra lối tắt khiến mã nguồn của bạn sạch sẽ hơn và hữu hiệu hơn. Những toán tử thông dụng nhất được liệt kê bên dưới:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Toán tửTênMục đíchVí dụViết tắt cho
+=Cộng gánCộng giá trị bên phải vào giá trị của biến bên trái, rồi trả về gía trị mới cho biếnx = 3;
+ x += 4;
x = 3;
+ x = x + 4;
-=Trừ gánTrừ giá trị của biến biến bên trái cho giá trị bên phải, rồi trả về giá trị mới cho biếnx = 6;
+ x -= 3;
x = 6;
+ x = x - 3;
*=Nhân gánNhân giá trị của biến bên trái với giá trị bên phải, rồi trả về gía trị mới cho biếnx = 2;
+ x *= 3;
x = 2;
+ x = x * 3;
/=Chia gánChia giá trị của biến biến bên trái cho giá trị bên phải, rồi trả về giá trị mới cho biếnx = 10;
+ x /= 5;
x = 10;
+ x = x / 5;
+ +

Thử gõ vài ví dụ phía trên vào console của bạn, để hiểu nguyên lý hoạt động của chúng. Trong mỗi trường hợp, thử đoán xem giá trị của chúng trước khi xuống dòng kế..

+ +

Bạn có thể vô tư sử dụng biến khác vào phía bên phải của mỗi biểu thức, chẳng hạn:

+ +
var x = 3; // x giữ giá trị 3
+var y = 4; // y giữ giá trị 4
+x *= y; // x giờ giữ giá trị 12
+ +
+

Ghi chú: Còn có nhiều toán tử gán khác nữa, nhưng bây giờ bạn chỉ cần học những toán tử trên thôi.

+
+ +

Học chủ động: định cỡ của hộp canvas

+ +

Trong bài luyện này, bạn sẽ thao tác với vài con số và toán tử để thay đổi kích thước của một chiếc hộp. Chiếc hộp được vẽ nên bởi API của trình duyệt tên là {{domxref("Canvas API", "", "", "true")}}. Bạn không cần quan tâm đến nguyên lý vận hành của nó — giờ chỉ cần tập trung vào phép tính thôi. Chiều rộng và chiều cao của chiếc hộp (theo pixels) được định nghĩa bởi hai biến xy, được khởi tạo với giá trị bằng 50.

+ +

{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/maths/editable_canvas.html", '100%', 620)}}

+ +

Mở trong cửa sổ mới

+ +

Trong hộp thoại mã nguồn chỉnh sửa được phía trên, có hai dòng được đặt trong comment mà chúng tôi muốn bạn cập nhật để khiến chiếc hộp phóng to/ thu nhỏ đến theo kích cỡ xác định, sử dụng toán tử và/ hoặc giá trị xác định trong mỗi trường hợp. Hãy thử theo bên dưới:

+ + + +

Đừng lo nếu nhỡ có làm sai gì đó. Bạn luôn có thể nhấn nút Reset để mọi thứ lại trở lại như ban đầu. Sau khi đã trả lời đúng tất cả câu hỏi phía trên, đừng ngần ngại chơi đùa với mã nguồn và tự tạo ra thử thách cho bản thân.

+ +

Toán tử so sánh

+ +

Đôi khi ta sẽ muốn kiểm tra true/false, rồi quyết định làm gì đó tiếp dựa trên kết quả của phép kiểm tra — để làm điều này ta dùng toán tử so sánh.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Toán tửTênMục đíchVí dụ
===Bằng chính xácKiểm tra xem liệu hai giá trị trái phải có giống hệt nhau hay không5 === 2 + 4
!==Không bằng chính xácTiểm tra xem liệu hai giá trị trái phải có không giống hệt nhau hay không5 !== 2 + 3
<Nhỏ hơnKiểm tra xem giá trị bên trái có nhỏ hơn giá trị bên phải hay không.10 < 6
>Lớn hơnKiểm tra xem giá trị bên trái có lớn hơn giá trị bên phải hay không.10 > 20
<=Nhỏ hơn hoặc bằngKiểm tra xem giá trị bên trái có nhỏ hơn hoặc bằng giá trị bên phải hay không3 <= 2
>=Lớn hơn hoặc bằngKiểm tra xem giá trị bên trái có lớn hơn hoặc bằng giá trị bên phải hay không.5 >= 4
+ +
+

Ghi chú: Có lẽ bạn sẽ thấy có người sử dụng ==!= trong mã nguồn của họ. Đây là những toán tử hợp lệ trong JavaScript, nhưng chúng khác với ===/!==. Hai toán tử trước kiểm tra sự giống nhau về giá trị nhưng không kiểm tra sự giống nhau về kiểu dữ liệu. Hai toán tử sau, kiểm tra chính xác sự giống nhau về cả giá trị lẫn kiểu dữ liệu. Toán tử so sánh chính xác thường gây ra ít lỗi hơn, nên chúng tôi đề nghị bạn dùng chúng.

+
+ +

Nếu bạn thử nhập những giá trị sau vào console, bạn sẽ thấy chúng đều trả về giá trị true/false — những giá trị boolean mà ta đã nhắc tới ở bài viết trước. Chúng cực kì hữu dụng bởi chúng giúp ta tạo quyết định trong chương trình của mình, và chúng được dùng mỗi khi ta cần đưa ra lựa chọn. Chẳng hạn, boolean có thể dùng để:

+ + + +

Ta sẽ học cách viết đống logic đó trong các bài viết sau khi học về câu điều kiện. Bây giờ, hãy xem qua ví dụ sau:

+ +
<button>Start machine</button>
+<p>The machine is stopped.</p>
+
+ +
var btn = document.querySelector('button');
+var txt = document.querySelector('p');
+
+btn.addEventListener('click', updateBtn);
+
+function updateBtn() {
+  if (btn.textContent === 'Start machine') {
+    btn.textContent = 'Stop machine';
+    txt.textContent = 'The machine has started!';
+  } else {
+    btn.textContent = 'Start machine';
+    txt.textContent = 'The machine is stopped.';
+  }
+}
+ +

{{EmbedGHLiveSample("learning-area/javascript/introduction-to-js-1/maths/conditional.html", '100%', 100)}}

+ +

Mở trong cửa sổ mới

+ +

Bạn có thể thấy toán tử so sánh bằng được dùng trong hàm updateBtn(). Trong trường hợp này, ta không so sánh hai biểu thức toán học có trả về cùng một giá trị hay không - ta đang kiểm tra xem liệu nội dung ký tự bên trong một nút bấm có chứa một xâu ký tự xác định không — nhưng nguyên lý hoạt động cũng tương tự. Nếu nút bấm có xâu ký tự là "Start machine" khi đã được nhấn, ta chuyển nhãn của nó thành "Stop machine", và cập nhật lại nhãn dán. Nếu nút bấm có xâu ký tự là "Stop machine" khi đã được nhấn, ta chuyển nó ngược lại.

+ +
+

Ghi chú: Việc chuyển tiếp liên tục giữa hai giá trị thường được gọi là toggle. Nó chuyển từ trạng thái này qua trạng thái kia — đèn bật, đèn tắt, vân vân.

+
+ +

Tóm lại

+ +

Trong bài viết này chúng tôi đã gợi ra thông tin căn bản bạn cần để biết về số trong JavaScript, cho lúc này. Bạn sẽ còn thấy các con số xuất hiện lại liên tục, xuyên suốt quá trình học JavaScript, thế nên giờ là lúc tốt nhất để học về chúng. Nếu bạn là một trong những người không yêu thương gì toán học, bạn sẽ thấy vui vì bài viết này khá là ngắn.

+ +

Trong bài viết tới, ta sẽ học về văn bản và cách JavaScript cho phép ta thao tác với chúng.

+ +
+

Ghi chú: Nếu bạn thực sự yêu toán và muốn đọc thêm về cách cài đặt chúng trong JavaScript, bạn có thể tìm vô số bài viết chi tiết trong khu vực chính về JavaScript của MDN. Những điểm đến thú vị có thể kể đến như là bài viết về Số và ngày thángBiểu thức và toán tử của chúng tôi.

+
+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/Variables", "Learn/JavaScript/First_steps/Strings", "Learn/JavaScript/First_steps")}}

+ +

Trong mô-đun này

+ + diff --git a/files/vi/learn/javascript/first_steps/strings/index.html b/files/vi/learn/javascript/first_steps/strings/index.html new file mode 100644 index 0000000000..df1650498d --- /dev/null +++ b/files/vi/learn/javascript/first_steps/strings/index.html @@ -0,0 +1,290 @@ +--- +title: Handling text — strings in JavaScript +slug: Learn/JavaScript/First_steps/Strings +translation_of: Learn/JavaScript/First_steps/Strings +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}
+ +

Tiếp theo chúng ta sẽ cùng tập trung vào chuỗi (string) — Trong lập trình chuỗi là một phần nhỏ của văn bản. Trong bài viết này chúng ta sẽ cùng tìm hiểu tất cả các đặc điểm chúng mà bạn cần phải biết về chuỗi khi học JavaScript, như là tạo chuỗi, escaping quotes trong chuỗi và kết hợp chuỗi lại với nhau.

+ + + + + + + + + + + + +
Yêu cầu: +

Trình độ máy tính cơ bản, có hiểu biết cơ bản về HTML, CSS và JavaScript.

+
Mục tiêu: +

Làm quen với những thứ cơ bản của chuỗi trong Javascript.

+
+ +

Sức mạnh của từ ngữ

+ +

Từ ngữ rất quan trọng với con người - Chúng là một phần của giao tiếp. Bởi vì Web được tạo nên từ một lượng lớn văn bản là vật trung gian giúp con người có thể giao tiếp và chia sẻ thông tin, sẽ hữu ích hơn nếu ta có thể làm chủ được toàn bộ từ ngữ xuất hiện trong nó. {{glossary("HTML")}} cung cấp cấu trúc và định nghĩa cho văn bản, {{glossary("CSS")}} cho phép ta có thể tạo kiểu một cách tỷ mỉ cho nó và JavaSript chứa một lượng các tính năng giúp cho việc thao tác lên văn bản, tạo những tin nhắn trang trọng tùy ý, biểu thị đúng nhãn văn bản khi cần thiết, sắp xếp thuận ngữ theo thứ tự mong muốn và nhiều hơn nữa.

+ +

Khá nhiều những chương trình mà chúng tôi đã giới thiệu với bạn trong khóa học này, đã có liên quan tới vài việc thao tác lên chuỗi.

+ +

Chuỗi — Khái niệm cơ bản

+ +

Chuỗi có vẻ tương tự với số khi ta mới lướt qua, nhưng khi bạn đào sâu hơn, bạn sẽ bắt đầu thấy một số sự khác biệt đáng lưu tâm. Cùng bắt đầu với việc nhập một vài dòng vào console để làm quen nhé. Chúng tôi đã cung cấp một console bên dưới (Bạn có thể mở console này ở một tab hoặc cửa sổ khác, hoặc sử dụng console của trình duyệt ở chế độ developer (browser developer console) nếu bạn thích).

+ + + +

{{ EmbedLiveSample('Hidden_code', '100%', 300, "", "", "hide-codepen-jsfiddle") }}

+ +

Creating a string

+ +
    +
  1. To start with, enter the following lines: +
    var string = 'The revolution will not be televised.';
    +string;
    + Just like we did with numbers, we are declaring a variable, initializing it with a string value, and then returning the value. The only difference here is that when writing a string, you need to surround the value with quotes.
  2. +
  3. If you don't do this, or miss one of the quotes, you'll get an error. Try entering the following lines: +
    var badString = This is a test;
    +var badString = 'This is a test;
    +var badString = This is a test';
    + These lines don't work because any text without quotes around it is assumed to be a variable name, property name, reserved word, or similar. If the browser can't find it, then an error is raised (e.g. "missing ; before statement"). If the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). If your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks.
  4. +
  5. The following will work if you previously defined the variable string — try it now: +
    var badString = string;
    +badString;
    + badString is now set to have the same value as string.
  6. +
+ +

Single quotes vs. double quotes

+ +
    +
  1. In JavaScript, you can choose single quotes or double quotes to wrap your strings in. Both of the following will work okay: +
    var sgl = 'Single quotes.';
    +var dbl = "Double quotes";
    +sgl;
    +dbl;
    +
  2. +
  3. There is very little difference between the two, and which you use is down to personal preference. You should choose one and stick to it, however; differently quoted code can be confusing, especially if you use the different quotes on the same string! The following will return an error: +
    var badQuotes = 'What on earth?";
    +
  4. +
  5. The browser will think the string has not been closed, because the other type of quote you are not using to contain your strings can appear in the string. For example, both of these are okay: +
    var sglDbl = 'Would you eat a "fish supper"?';
    +var dblSgl = "I'm feeling blue.";
    +sglDbl;
    +dblSgl;
    +
  6. +
  7. However, you can't include the same quote mark inside the string if it's being used to contain them. The following will error, as it confuses the browser as to where the string ends: +
    var bigmouth = 'I've got no right to take my place...';
    + This leads us very nicely into our next subject.
  8. +
+ +

Escaping characters in a string

+ +

To fix our previous problem code line, we need to escape the problem quote mark. Escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. In JavaScript, we do this by putting a backslash just before the character. Try this:

+ +
var bigmouth = 'I\'ve got no right to take my place...';
+bigmouth;
+ +

This works fine. You can escape other characters in the same way, e.g. \",  and there are some special codes besides. See Escape notation for more details.

+ +

Concatenating strings

+ +
    +
  1. Concatenate is a fancy programming word that means "join together". Joining together strings in JavaScript uses the plus (+) operator, the same one we use to add numbers together, but in this context it does something different. Let's try an example in our console. +
    var one = 'Hello, ';
    +var two = 'how are you?';
    +var joined = one + two;
    +joined;
    + The result of this is a variable called joined, which contains the value "Hello, how are you?".
  2. +
  3. In the last instance, we just joined two strings together, but you can do as many as you like, as long as you include a + between each one. Try this: +
    var multiple = one + one + one + one + two;
    +multiple;
    +
  4. +
  5. You can also use a mix of variables and actual strings. Try this: +
    var response = one + 'I am fine — ' + two;
    +response;
    +
  6. +
+ +
+

Note: When you enter an actual string in your code, enclosed in single or double quotes, it is called a string literal.

+
+ +

Concatenation in context

+ +

Let's have a look at concatenation being used in action — here's an example from earlier in the course:

+ +
<button>Press me</button>
+ +
var button = document.querySelector('button');
+
+button.onclick = function() {
+  var name = prompt('What is your name?');
+  alert('Hello ' + name + ', nice to see you!');
+}
+ +

{{ EmbedLiveSample('Concatenation_in_context', '100%', 50, "", "", "hide-codepen-jsfiddle") }}

+ +

Here we're using a {{domxref("window.prompt()", "window.prompt()")}} function in line 4, which asks the user to answer a question via a popup dialog box then stores the text they enter inside a given variable — in this case name. We then use an {{domxref("window.alert()", "window.alert()")}} function in line 5 to display another popup containing a string we've assembled from two string literals and the name variable, via concatenation.

+ +

Numbers vs. strings

+ +
    +
  1. So what happens when we try to add (or concatenate) a string and a number? Let's try it in our console: +
    'Front ' + 242;
    +
    + You might expect this to throw an error,  but it works just fine. Trying to represent a string as a number doesn't really make sense, but representing a number as a string does, so the browser rather cleverly converts the number to a string and concatenates the two strings together.
  2. +
  3. You can even do this with two numbers — you can force a number to become a string by wrapping it in quote marks. Try the following (we are using the typeof operator to check whether the variable is a number or a string): +
    var myDate = '19' + '67';
    +typeof myDate;
    +
  4. +
  5. If you have a numeric variable that you want to convert to a string but not change otherwise, or a string variable that you want to convert to a number but not change otherwise, you can use the following two constructs: +
      +
    • The {{jsxref("Number")}} object will convert anything passed to it into a number, if it can. Try the following: +
      var myString = '123';
      +var myNum = Number(myString);
      +typeof myNum;
      +
    • +
    • On the other hand, every number has a method called toString() that will convert it to the equivalent string. Try this: +
      var myNum = 123;
      +var myString = myNum.toString();
      +typeof myString;
      +
    • +
    + These constructs can be really useful in some situations. For example, if a user enters a number into a form text field, it will be a string. However, if you want to add this number to something, you'll need it to be a number, so you could pass it through Number() to handle this. We did exactly this in our Number Guessing Game, in line 61.
  6. +
+ +

Conclusion

+ +

So that's the very basics of strings covered in JavaScript. In the next article we'll build on this, looking at some of the built-in methods available to strings in JavaScript and how we can use them to manipulate our strings into just the form we want.

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/Math", "Learn/JavaScript/First_steps/Useful_string_methods", "Learn/JavaScript/First_steps")}}

+ +

 

+ +

In this module

+ + + +

 

diff --git a/files/vi/learn/javascript/first_steps/what_is_javascript/index.html b/files/vi/learn/javascript/first_steps/what_is_javascript/index.html new file mode 100644 index 0000000000..a8c837a2e2 --- /dev/null +++ b/files/vi/learn/javascript/first_steps/what_is_javascript/index.html @@ -0,0 +1,422 @@ +--- +title: JavaScript là Gì? +slug: Learn/JavaScript/First_steps/What_is_JavaScript +translation_of: Learn/JavaScript/First_steps/What_is_JavaScript +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}
+ +

Chào mừng đến khóa học JavaScript cơ bản của MDN! Trong bài đầu tiên chúng ta sẽ nhìn nhận JavaScript từ góc độ tổng quát, trả lời các câu hỏi như "JavaScript là gì?" và "nó có khả năng gì?" cũng như giúp bạn làm quen với các chức năng của JavaScript.

+ + + + + + + + + + + + +
Yêu cầu: +

Sử dụng máy cơ bản, hiểu HTML và CSS mức độ căn bản

+
Mục tiêu: +

Làm quen với JavaScript, tìm hiểu về ứng dụng của JavaScript và cách tích hợp chúng vào một trang web.

+
+ +

A high-level definition

+ +

JavaScript là một ngôn ngữ lập trình hoặc ngôn ngữ kịch bản cho phép triển khai những chức năng phức tạp trên trang web như hiển thị các cập nhật nội dung kịp thời, tương tác với bản đồ, hoạt cảnh 2D/3D vv... - điều có sự hỗ trợ của JavaScript. Nó là lớp thứ ba của chiếc bánh tiêu chuẩn của các công nghệ web, hai trong số chúng (HTML và CSS) đã được chúng tôi trình bày rất chi tiết trong các phần khác của Learning Area.

+ +

+ + + +

Ba lớp công nghệ xếp chồng lên nhau một cách thích hợp. Hãy xem xét ví dụ một đoạn văn bản đơn giản. Chúng ta có thể đánh dấu đoạn văn bảng bằng HTML.

+ +
<p>Player 1: Chris</p>
+ +

+ +

Sau đó thêm một vài đoạn CSS giúp tăng tính thẩm mỹ cho đoạn văn:

+ +
p {
+  font-family: 'helvetica neue', helvetica, sans-serif;
+  letter-spacing: 1px;
+  text-transform: uppercase;
+  text-align: center;
+  border: 2px solid rgba(0,0,200,0.6);
+  background: rgba(0,0,200,0.3);
+  color: rgba(0,0,200,0.6);
+  box-shadow: 1px 1px 2px rgba(0,0,200,0.4);
+  border-radius: 10px;
+  padding: 3px 10px;
+  display: inline-block;
+  cursor: pointer;
+}
+ +

+ +

Và cuối cùng, chúng ta có thể áp dụng JavaScript vào đoạn văn để tăng tính tương tác.

+ +
const para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  let name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+
+ +

{{ EmbedLiveSample('A_high-level_definition', '100%', 80, "", "", "hide-codepen-jsfiddle") }}

+ +

Thử nhấp vào phiên bản cuối cùng của đoạn văn để thấy cách nó hoạt động (bạn cũng có thể tìm thấy ví dụ này trên GitHub — xem mã nguồn: source code, hoặc chạy trực tiếp: run it live)!

+ +

JavaScript có thể làm được nhiều hơn thế  — Cùng khám phá chi tiết hơn.

+ +

So what can it really do?

+ +

Bên trong ngôn ngữ JavaScript bao gồm một vài tính năng lập trình phổ biến cho phép bạn thực hiện một vài điều như:

+ + + +

Tuy nhiên thứ mà thậm chí còn thú vị hơn nữa là các lớp tính năng (functionality) được xây dựng trên lõi của ngôn ngữ JavaScript. Cái được gọi là Giao Diện Lập Trình Ứng Dụng (Application Programming Interfaces-APIs) trao thêm cho bạn siêu sức mạnh để sử dụng trong code JavaScript.

+ +

APIs là các bộ code được dựng sẵn cho phép một nhà pháp triển (developer) triển khai các chương trình mà nếu thiếu nó sẽ khó hoặc bất khả thi để triển khai. Chúng hoạt động trong lập trình tương tự như những bộ nội thất làm sẵn cho việc xây nhà — sẽ dễ dàng hơn nhiều nếu lắp ráp một kệ sách với gỗ đã gia công theo thiết kế và ốc vít có sẵn hơn là tự tìm gỗ nguyên liệu, tự gia công theo kích cỡ đã thiết kết, tìm ốc vít đúng cỡ rồi lắp ráp thành một kệ sách.

+ +

APIs thường được chia thành hai loại:

+ +

+ +

Browser APIs (APIs Trình Duyệt) được tích hợp sẵn trong trình duyệt web, có khả năng phơi bày dữ liệu từ môi trường máy tính xung quanh hoặc làm những điều phức tạp hữu ích. Ví dụ:

+ + + +
+

Note: Many of the above demos won't work in an older browser — when experimenting, it's a good idea to use a modern browser like Firefox, Chrome, Edge or Opera to run your code in. You will need to consider cross browser testing in more detail when you get closer to delivering production code (i.e. real code that real customers will use).

+
+ +

Third party APIs are not built into the browser by default, and you generally have to grab their code and information from somewhere on the Web. For example:

+ + + +
+

Note: These APIs are advanced, and we'll not be covering any of these in this module. You can find out much more about these in our Client-side web APIs module.

+
+ +

There's a lot more available, too! However, don't get over excited just yet. You won't be able to build the next Facebook, Google Maps, or Instagram after studying JavaScript for 24 hours — there are a lot of basics to cover first. And that's why you're here — let's move on!

+ +

What is JavaScript doing on your page?

+ +

Here we'll start actually looking at some code, and while doing so explore what actually happens when you run some JavaScript in your page.

+ +

Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our How CSS works article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).

+ +

+ +

The JavaScript is executed by the browser's JavaScript engine, after the HTML and CSS have been assembled and put together into a web page. This ensures that the structure and style of the page are already in place by the time the JavaScript starts to run.

+ +

This is a good thing, as a very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above). If the JavaScript loaded and tried to run before the HTML and CSS were there to affect, then errors would occur.

+ +

Browser security

+ +

Each browser tab is its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. This is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.

+ +
+

Note: There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.

+
+ +

JavaScript running order

+ +

When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. For example, let's return to the block of JavaScript we saw in our first example:

+ +
const para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  let name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+ +

Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updateName() code block (lines 5–8) is run. The updateName() code block (these types of reusable code blocks are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display.

+ +

If you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the browser developer consoleTypeError: para is undefined. This means that the para object does not exist yet, so we can't add an event listener to it.

+ +
+

Note: This is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them.

+
+ +

Interpreted versus compiled code

+ +

You might hear the terms interpreted and compiled in the context of programming. In interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.

+ +

Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer. For example, C/C++ are compiled into assembly language that is then run by the computer.

+ +

JavaScript is a lightweight interpreted programming language. Both approaches have different advantages, which we won't discuss at this point.

+ +

Server-side versus client-side code

+ +

You might also hear the terms server-side and client-side code, especially in the context of web development. Client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser. In this module we are explicitly talking about client-side JavaScript.

+ +

Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser. Examples of popular server-side web languages include PHP, Python, Ruby, ASP.NET and... JavaScript! JavaScript can also be used as a server-side language, for example in the popular Node.js environment — you can find out more about server-side JavaScript in our Dynamic Websites – Server-side programming topic.

+ +

Dynamic versus static code

+ +

The word dynamic is used to describe both client-side JavaScript, and server-side languages — it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required. Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, filling it with data requested from the server, then displaying the table in a web page shown to the user. The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.

+ +

A web page with no dynamically updating content is referred to as static — it just shows the same content all the time.

+ +

How do you add JavaScript to your page?

+ +

JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses {{htmlelement("link")}} elements to apply external stylesheets and {{htmlelement("style")}} elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the {{htmlelement("script")}} element. Let's learn how this works.

+ +

Internal JavaScript

+ +
    +
  1. First of all, make a local copy of our example file apply-javascript.html. Save it in a directory somewhere sensible.
  2. +
  3. Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.
  4. +
  5. Next, go to your text editor and add the following in your head — just before your closing </head> tag: +
    <script>
    +
    +  // JavaScript goes here
    +
    +</script>
    +
  6. +
  7. Now we'll add some JavaScript inside our {{htmlelement("script")}} element to make the page do something more interesting — add the following code just below the "// JavaScript goes here" line: +
    document.addEventListener("DOMContentLoaded", function() {
    +  function createParagraph() {
    +    let para = document.createElement('p');
    +    para.textContent = 'You clicked the button!';
    +    document.body.appendChild(para);
    +  }
    +
    +  const buttons = document.querySelectorAll('button');
    +
    +  for(let i = 0; i < buttons.length ; i++) {
    +    buttons[i].addEventListener('click', createParagraph);
    +  }
    +});
    +
  8. +
  9. Save your file and refresh the browser — now you should see that when you click the button, a new paragraph is generated and placed below.
  10. +
+ +
+

Note: If your example doesn't seem to work, go through the steps again and check that you did everything right. Did you save your local copy of the starting code as a .html file? Did you add your {{htmlelement("script")}} element just before the </head> tag? Did you enter the JavaScript exactly as shown? JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.

+
+ +
+

Note: You can see this version on GitHub as apply-javascript-internal.html (see it live too).

+
+ +

External JavaScript

+ +

This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.

+ +
    +
  1. First, create a new file in the same directory as your sample HTML file. Call it script.js — make sure it has that .js filename extension, as that's how it is recognized as JavaScript.
  2. +
  3. Replace your current {{htmlelement("script")}} element with the following: +
    <script src="script.js" defer></script>
    +
  4. +
  5. Inside script.js, add the following script: +
    function createParagraph() {
    +  let para = document.createElement('p');
    +  para.textContent = 'You clicked the button!';
    +  document.body.appendChild(para);
    +}
    +
    +const buttons = document.querySelectorAll('button');
    +
    +for(let i = 0; i < buttons.length ; i++) {
    +  buttons[i].addEventListener('click', createParagraph);
    +}
    +
  6. +
  7. Save and refresh your browser, and you should see the same thing! It works just the same, but now we've got our JavaScript in an external file. This is generally a good thing in terms of organizing your code and making it reusable across multiple HTML files. Plus, the HTML is easier to read without huge chunks of script dumped in it.
  8. +
+ +
+

Note: You can see this version on GitHub as apply-javascript-external.html and script.js (see it live too).

+
+ +

Inline JavaScript handlers

+ +

Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might look something like this:

+ +
+
function createParagraph() {
+  let para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+ +
<button onclick="createParagraph()">Click me!</button>
+
+ +

You can try this version of our demo below.

+ +

{{ EmbedLiveSample('inline_js_example', '100%', 150, "", "", "hide-codepen-jsfiddle") }}

+ +

This demo has exactly the same functionality as in the previous two sections, except that the {{htmlelement("button")}} element includes an inline onclick handler to make the function run when the button is pressed.

+ +

Please don't do this, however. It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the onclick="createParagraph()" attribute on every button you wanted the JavaScript to apply to.

+ +

Using a pure JavaScript construct allows you to select all the buttons using one instruction. The code we used above to serve this purpose looks like this:

+ +
const buttons = document.querySelectorAll('button');
+
+for(let i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +

This might be a bit longer than the onclick attribute, but it will work for all buttons — no matter how many are on the page, nor how many are added or removed. The JavaScript does not need to be changed.

+ +
+

Note: Try editing your version of apply-javascript.html and add a few more buttons into the file. When you reload, you should find that all of the buttons when clicked will create a paragraph. Neat, huh?

+
+ +

Script loading strategies

+ +

There are a number of issues involved with getting scripts to load at the right time. Nothing is as simple as it seems! A common problem is that all the HTML on a page is loaded in the order in which it appears. If you are using JavaScript to manipulate elements on the page (or more accurately, the Document Object Model), your code won't work if the JavaScript is loaded and parsed before the HTML you are trying to do something to.

+ +

In the above code examples, in the internal and external examples the JavaScript is loaded and run in the head of the document, before the HTML body is parsed. This could cause an error, so we've used some constructs to get around it.

+ +

In the internal example, you can see this structure around the code:

+ +
document.addEventListener("DOMContentLoaded", function() {
+  ...
+});
+ +

This is an event listener, which listens for the browser's "DOMContentLoaded" event, which signifies that the HTML body is completely loaded and parsed. The JavaScript inside this block will not run until after that event is fired, therefore the error is avoided (you'll learn about events later in the course).

+ +

In the external example, we use a more modern JavaScript feature to solve the problem, the defer attribute, which tells the browser to continue downloading the HTML content once the <script> tag element has been reached.

+ +
<script src="script.js" defer></script>
+ +

In this case both the script and the HTML will load simultaneously and the code will work.

+ +
+

Note: In the external case, we did not need to use the DOMContentLoaded event because the defer attribute solved the problem for us. We didn't use the defer solution for the internal JavaScript example because defer only works for external scripts.

+
+ +

An old-fashioned solution to this problem used to be to put your script element right at the bottom of the body (e.g. just before the </body> tag), so that it would load after all the HTML has been parsed. The problem with this solution is that loading/parsing of the script is completely blocked until the HTML DOM has been loaded. On larger sites with lots of JavaScript, this can cause a major performance issue, slowing down your site.

+ +

async and defer

+ +

There are actually two ways we can bypass the problem of the blocking script — async and defer. Let's look at the difference between these two.

+ +

Async scripts will download the script without blocking rendering the page and will execute it as soon as the script finishes downloading. You get no guarantee that scripts will run in any specific order, only that they will not stop the rest of the page from displaying. It is best to use async when the scripts in the page run independently from each other and depend on no other script on the page.

+ +

For example, if you have the following script elements:

+ +
<script async src="js/vendor/jquery.js"></script>
+
+<script async src="js/script2.js"></script>
+
+<script async src="js/script3.js"></script>
+ +

You can't rely on the order the scripts will load in. jquery.js may load before or after script2.js and script3.js and if this is the case, any functions in those scripts depending on jquery will produce an error because jquery will not be defined at the time the script runs.

+ +

defer will run the scripts in the order they appear in the page and execute them as soon as the script and content are downloaded:

+ +
<script defer src="js/vendor/jquery.js"></script>
+
+<script defer src="js/script2.js"></script>
+
+<script defer src="js/script3.js"></script>
+ +

All the scripts with the defer attribute will load in the order they appear on the page. So in the second example, we can be sure that jquery.js will load before script2.js and script3.js and that script2.js will load before script3.js.

+ +

To summarize:

+ + + +

Comments

+ +

As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist simply to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after six months and can't remember what you did). Comments are very useful, and you should use them often, particularly for larger applications. There are two types:

+ + + +

So for example, we could annotate our last demo's JavaScript with comments like so:

+ +
// Function: creates a new paragraph and appends it to the bottom of the HTML body.
+
+function createParagraph() {
+  let para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+
+/*
+  1. Get references to all the buttons on the page in an array format.
+  2. Loop through all the buttons and add a click event listener to each one.
+
+  When any button is pressed, the createParagraph() function will be run.
+*/
+
+const buttons = document.querySelectorAll('button');
+
+for (let i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +
+

Note: In general more comments is usually better than less, but you should be careful if you find yourself adding lots of comments to explain what variables are (your variable names perhaps should be more intuitive), or to explain very simple operations (maybe your code is overcomplicated).

+
+ +

Summary

+ +

So there you go, your first step into the world of JavaScript. We've begun with just theory, to start getting you used to why you'd use JavaScript and what kind of things you can do with it. Along the way, you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.

+ +

JavaScript may seem a bit daunting right now, but don't worry — in this course, we will take you through it in simple steps that will make sense going forward. In the next article, we will plunge straight into the practical, getting you to jump straight in and build your own JavaScript examples.

+ + + +

{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/vi/learn/javascript/index.html b/files/vi/learn/javascript/index.html new file mode 100644 index 0000000000..c1ccb8de4b --- /dev/null +++ b/files/vi/learn/javascript/index.html @@ -0,0 +1,82 @@ +--- +title: JavaScript +slug: Learn/JavaScript +tags: + - Beginner + - CodingScripting + - JavaScript + - JavaScripting beginner + - Landing + - Module + - NeedsTranslation + - Topic + - TopicStub + - 'l10n:priority' +translation_of: Learn/JavaScript +--- +
{{LearnSidebar}}
+ +

{{Glossary("JavaScript")}} là ngôn ngữ lập trình cho phép bạn triển khai những thứ phức tạp trên trang web - mỗi khi trang web hoạt động nhiều hơn là chỉ hiển thị thông tin tĩnh để bạn xem - hiển thị cập nhật nội dung kịp thời, bản đồ tương tác, hoạt ảnh 2D / 3D đồ họa hoặc cuộn các hộp video, v.v. - bạn có thể đặt cược rằng JavaScript dùng để làm những việc đó.

+ +

BẠN ĐANG MUỐN TRỞ THÀNH MỘT FRONT-END DEVELOPER ?

+ +

Chúng tôi đã tổng hợp một khóa học bao gồm tất cả thông tin cần thiết mà bạn cần để hướng tới mục tiêu của mình.

+ +

Get started

+ +

Điều kiện tiên quyết

+ +

JavaScript được cho là khó học hơn các công nghệ liên quan như HTML và CSS. Trước khi cố gắng học JavaScript, bạn nên làm quen trước với ít nhất hai công nghệ này trước tiên, và có thể cả các công nghệ khác nữa. Bắt đầu bằng cách học tập qua các đường dẫn sau :

+ + + +

Nếu bạn có kinh nghiệm lập trình với các ngôn ngữ khác thì nó sẽ giúp ích rất nhiều.

+ +

Sau khi làm quen với các kiến thức cơ bản về JavaScript, bạn đã sẵn sàng để tìm hiểu về các chủ đề nâng cao hơn, ví dự:

+ + + +

Modules

+ +

Chủ đề này đã được chia nhỏ thành các phần, để tiện cho việc học và tìm hiểu chúng.

+ +
+
JavaScript first steps
+
Trong phần đầu tiên của bài hướng dẫn JavaScript, đầu tiên chúng ta trả lời một số câu hỏi cơ bản như "JavaScript là gì ?", "Nó trong như thế nào?", và "Nó có thể làm gì ?", trước khi chuyển qua phần hướng dẫn bạn trải nghiệm thực hành viết JavaScript. Sau đó,chúng ta sẽ thảo luận chi tiết về một số chức năng chính của JavaScript, như : biến, chuỗi, các số và mảng.
+
JavaScript building blocks
+
Trong phần này, chúng ta tiếp tục đề cập đến tất cả những tính năng cơ bản của JavaScript, sau đó hãy chuyển sự chú ý sang các loại khối lệnh thường gặp như : câu lệnh điều kiện, vòng lặp, hàm và sự kiện . Có lẽ bạn đã nhìn thấy những thứ trên trong khóa học này rồi nhưng đó mới chỉ là thoáng qua thôi — ở đây chúng ta sẽ thảo luận một cách rõ ràng.
+
Introducing JavaScript objects
+
Trong JavaScript, mọi thứ đều được coi là objects, từ các tính năng cốt lõi của JavaScript như chuỗi và mảng cho đến các APIs của trình duyệt được xây dựng trên JavaScript. Bạn thậm chí có thể tự tạo ra các objects của riêng mình để đóng gói các hàm và biến liên quan thành các packages hiệu quả. Bản chất hướng đối tượng của JavaScript là thứ vô cùng quan trọng bạn phải hiểu nếu như bạn muốn tiến xa hơn với ngôn ngữ và viết code hiệu quả hơn, do đó chúng tôi đã chia nhỏ khóa học thành từng phần nhỏ để giúp bạn học hiệu quả hơn. Ở đây chúng tôi dạy chi tiết về lý thuyết các object và các cú pháp, hãy nhìn xem làm thế nào để tạo được một object của bạn, và hãy giải thích dữ liệu JSON là gì và làm thế nào để làm việc với nó.
+
Client-side web APIs
+
Khi bạn viết JavaScript ở phía máy khách cho một website hay một ứng dụng, bạn không thể làm tốt nếu không sử dụng  APIs — giao diện dùng để thao tác các khía cạnh khác nhau của trình duyệt và hệ điều hành mà trang web đang chạy, hoặc thậm chí là dữ liệu từ các web sites hoặc dịch vụ khác. Trong phần này chúng ta sẽ cùng tìm hiểu APIs là gì, và làm thế nào để sử dụng một số APIs phổ biến nhất mà chắc chắn bạn sẽ thường sử dụng chúng trong công việc phát triển phần mềm của mình. 
+
+ +

Giải quyết một số vấn đề thường gặp của JavaScript

+ +

Sử dụng JavaScript để giải quyết một số vấn đề thường gặp cung cấp nhưng đường dẫn đến các phần của nội dung để để giải thích làm thế nào để sử dụng JavaScript để giải quyết các vấn đề thường gặp khi tạo một trang web.

+ +

Xem thêm

+ +
+
JavaScript on MDN
+
Cổng vào cho tài liệu core JavaScript trên MDN - đây là nơi bạn sẽ tìm thấy các tài liệu tham khảo mở rộng về tất cả các khía cạnh của ngôn ngữ JavaScript và một số hướng dẫn nâng cao dành cho những người dùng JavaScript có kinh nghiệm.
+
+ +
+
Learn JavaScript
+
Một nguồn tài nguyên tuyệt vời cho các nhà phát triển web đầy tham vọng - Học JavaScript trong môi trường tương tác, với các bài học ngắn và bài kiểm tra có tính tương tác, được định hướng bởi các bài đánh giá tự động. 40 bài học đầu tiên là miễn phí và bạn có thể mua toàn bộ khoá học với một khoản phí nhỏ.
+
JavaScript Fundamentals on EXLskills
+
Học JavaScript miễn phí với khóa học mã nguồn mở EXLskills giới thiệu tất cả những gì bạn cần để bắt đầu xây dựng ứng dụng bằng JS.
+
+ +
+
Coding math
+
Một loạt các video hướng dẫn tuyệt vời để dạy bạn những phép toán cần biết để trở thành một lập trình viên hiệu quả, bởi Keith Peters.
+
diff --git a/files/vi/learn/javascript/objects/index.html b/files/vi/learn/javascript/objects/index.html new file mode 100644 index 0000000000..adaad99507 --- /dev/null +++ b/files/vi/learn/javascript/objects/index.html @@ -0,0 +1,42 @@ +--- +title: Introducing JavaScript objects +slug: Learn/JavaScript/Objects +translation_of: Learn/JavaScript/Objects +--- +
{{LearnSidebar}}
+ +
Trong JavaScript, hầu hết mọi thứ đều là các đối tượng, từ các tính nắng cốt lõi của JavaScript như chuỗi và mảng đến các {{Glossary("API", "APIs")}} của trình duyệt được xây dựng dựa trên JavaScript. Thậm chí bạn có thể tự tạo các đối tượng để bao đóng các hàm và các biến thành các gói và hoạt động như một kho chứa dữ liệu. Bản chất của JavaScript là dựa trên đối tượng, đây là hiểu biết quan trọng nếu bạn muốn tìm hiểu sâu hơn về ngôn ngữ này. Do đó, chúng tôi cung cấp mô đun này để giúp bạn. Chúng tôi trình bày chi tiết về nguyên lý và cú pháp đối tượng, sau đó là cách để bạn tự tạo các đối tượng cho riêng mình.
+ +

Điều kiện tiên quyết

+ +

Trước khi bắt đầu mô đun này, bạn cần có hiểu biết về {{Glossary("HTML")}} và {{Glossary("CSS")}}. Bạn có thể tìm hiểu qua Introduction to HTMLIntroduction to CSS trước khi bắt đầu học JavaScript.

+ +

Bạn cũng cần có hiểu biết cơ bản về JavaScript. Trước khi bắt đầu nghiên cứu mô đun này, bạn nên tìm hiểu JavaScript first stepsJavaScript building blocks.

+ +
+

Chú ý: Nếu bạn đang làm việc trên các thiết bị (máy tính bàn/máy tính bản/các thiết bị khác) mà không thể tạo các tệp riêng trên đó thì bạn có thể thử gõ mã trên JSBin hoặc Thimble.

+
+ +

Các hướng dẫn

+ +
+
Cơ bản về đối tượng
+
In the first article looking at JavaScript objects, we'll look at fundamental JavaScript object syntax, and revisit some JavaScript features we've already looked at earlier on in the course, reiterating the fact that many of the features you've already dealt with are in fact objects.
+
Hướng đối tượng trong JavaScript cho người mới học
+
With the basics out of the way, we'll now focus on object-oriented JavaScript (OOJS) — this article presents a basic view of object-oriented programming (OOP) theory, then explores how JavaScript emulates object classes via constructor functions, and how to create object instances.
+
Nguyên mẫu của đối tượng
+
Prototypes are the mechanism by which JavaScript objects inherit features from one another, and they work differently to inheritance mechanisms in classical object-oriented programming languages. In this article we explore that difference, explain how prototype chains work, and look at how the prototype property can be used to add methods to existing constructors.
+
Kế thừa trong JavaScript
+
With most of the gory details of OOJS now explained, this article shows how to create "child" object classes (constructors) that inherit features from their "parent" classes. In addition, we present some advice on when and where you might use OOJS.
+
Làm việc với định dạng dữ liệu JSON
+
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax, which is commonly used for representing and transmitting data on web sites (i.e. sending some data from the server to the client, so it can be displayed on a web page). You'll come across it quite often, so in this article we give you all you need to work with JSON using JavaScript, including parsing the JSON so you can access data items within it and writing your own JSON.
+
Luyện tập xây dựng đối tượng
+
In previous articles we looked at all the essential JavaScript object theory and syntax details, giving you a solid base to start from. In this article we dive into a practical exercise, giving you some more practice in building custom JavaScript objects, which produce something fun and colorful — some colored bouncing balls.
+
+ +

Assessments

+ +
+
Adding features to our bouncing balls demo
+
In this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it.
+
diff --git a/files/vi/learn/javascript/objects/inheritance/index.html b/files/vi/learn/javascript/objects/inheritance/index.html new file mode 100644 index 0000000000..56fb732295 --- /dev/null +++ b/files/vi/learn/javascript/objects/inheritance/index.html @@ -0,0 +1,440 @@ +--- +title: Inheritance in JavaScript +slug: Learn/JavaScript/Objects/Inheritance +translation_of: Learn/JavaScript/Objects/Inheritance +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}
+ +

Lúc này chúng ta đã timnf hiểu hầu hết về OOJS, bài viết này sẽ nói về cách để tạo ra một đối tượng "child" classes (constructors), thứ kế thừa các đặc trưng từ "parent" classes. Thêm nữa, chúng tôi sẽ chỉ cho bạn khi nào và ở đâu bạn có thể sử dụng OOJS, và cách mà các classes được xử lý trong cú pháp ECMAScript.

+ + + + + + + + + + + + +
Điều kiện:Kiến thức cơ bản về máy tính, hiểu biết về HTML và CSS, đã quen với Javsacript căn bản (xem First steps và Building blocks) và OOJS căn bản (xem Introduction to objects).
Mục tiêu:Hiểu về cách thực hiện việc kế thừa trong Javascript.
+ +

Prototypal inheritance

+ +

Ở nhứng bài trước chúng ta đã thực hiện việc kế thừa — chúng ta đã thấy cách mà prototype chains hoạt động, và cách mà các thành phần được kế thừa bằng cách đi ngược lên chuỗi prototype. Nhưng hầu hết chúng chỉ liên quan đến kế thừa từ function. Làm sao để tạo ra một object trong Javascript kế thừa từ một object khác?

+ +

Hãy cùng tìm hiểu với một ví dụ cụ thể:

+ +

Getting started

+ +

Đầu tiên, hãy tạo một bản copy của file oojs-class-inheritance-start.html (xem nó hoạt động: running live). Bạn sẽ thấy có cùng một constructor Person() mà chúng ta sử dụng trong các bài trước, và một chút thay đổi — chúng tôi chỉ định nghĩa các properties trong constructor:

+ +
function Person(first, last, age, gender, interests) {
+  this.name = {
+    first,
+    last
+  };
+  this.age = age;
+  this.gender = gender;
+  this.interests = interests;
+};
+ +

Các methods đều được định nghĩa trong prototype của constructor. Ví dụ:

+ +
Person.prototype.greeting = function() {
+  alert('Hi! I\'m ' + this.name.first + '.');
+};
+ +
+

Ghi chú: Trong source code, bạn sẽ thấy các methods bio() và farewell() được định nghĩa. Lát nữa bạn sẽ thấy cách chúng được kế thừa bởi các constructors khác.

+
+ +

Chúng ta muốn tạo một class Teacher, như đã mô tả trong định nghĩa ban đầu về object-oriented, là class kế thừa mọi thành phần từ Person, và có cả:

+ +
    +
  1. Một property mới, subject — nó sẽ chứa tên môn học mà teacher dạy.
  2. +
  3. Một method greeting() đã được chỉnh sửa sao cho trang trọng hơn so với method greeting() ban đầu — để phù hợp hơn khi một giáo viên nói chuyện với một học sinh ở trường.
  4. +
+ +

Định nghĩa hàm Teacher() constructor

+ +

Đầu tiên chúng ta cần tạo một Teacher() constructor — hãy thêm đoạn code bên dưới vào source code:

+ +
function Teacher(first, last, age, gender, interests, subject) {
+  Person.call(this, first, last, age, gender, interests);
+
+  this.subject = subject;
+}
+ +

Nhìn có vẻ giống với Person constructor, nhưng có một vài điều khác lạ mà chúng ta chưa từng thấy trước đó — hàm call(). Hàm này cho phép bạn gọi một function được định nghĩa ở một nơi khác. Tham số đầu tiên có giá trị this mà bạn muốn sử dụng khi đang thực thi function, và các tham số khác sẽ được chuyển cho function khi nó được gọi.

+ +

Chúng ta muốn Teacher() constructor có cùng tham số với Person() constructor mà nó kế thừa, nên chúng ta chỉ định chúng như các tham số khi gọi hàm call().

+ +

Dòng cuối cùng trong constructor chỉ đơn giản định nghĩa property subject.mà chỉ teachers có, và people không có

+ +

Nhưng chúng ta cũng có thể thực hiện điều này như sau:

+ +
function Teacher(first, last, age, gender, interests, subject) {
+  this.name = {
+    first,
+    last
+  };
+  this.age = age;
+  this.gender = gender;
+  this.interests = interests;
+  this.subject = subject;
+}
+ +

Nhưng đó là định nghĩa một properties mới, không kế thừa từ Person(), không giống như những gì chúng ta định làm. Nó cũng khiến code dài dòng hơn.

+ +

Kế thừa từ một constructor không có tham số

+ +

Lưu ý rằng nếu constructor mà bạn đang kế thừa không nhận các giá trị properties của nó từ tham số, bạn không cần thêm các tham số vào call(). Vậy, nếu bạn viết một vài dòng code như sau:

+ +
function Brick() {
+  this.width = 10;
+  this.height = 20;
+}
+ +

Bạn có thể kế thừa các properties width và height (cũng như các bước khác đã được mô tả bên dưới):

+ +
function BlueGlassBrick() {
+  Brick.call(this);
+
+  this.opacity = 0.5;
+  this.color = 'blue';
+}
+ +

Chú ý rằng chúng ta chỉ chỉ định this bên trong call() — Không có tham số nào là bắt buộc vì chúng ta không kế thừa bất cứ properties nào từ cha nó thông qua tham số.

+ +

Cấu hình prototype của Teacher() và về constructor

+ +

Mọi thứ đều ổn, nhưng có một vấn đề. Chúng ta vừa định nghĩa một constructor mới, và nó có prototype property, được mặc định là tham chiếu đến hàm constructor của nó. Nó không chứa các method trong property prototype của constructor của Person. Để thấy điều này, nhập Object.getOwnPropertyNames(Teacher.prototype) vào màn hình Javascript console. Sau đó, thay thế Teacher thành Person. Constructor cũng không kế thừa các methods đó. Đề thấy điều này, hãy so sánh kết quả của Person.prototype.greeting và Teacher.prototype.greeting. Chúng ta cần các methods của Teacher() để kế thừa các methods được định nghĩa trong prototype của Person(). Làm sao để thực hiện việc này?

+ +
    +
  1. Thêm dòng code sau vào dưới phần đã thêm vào trước đó: +
    Teacher.prototype = Object.create(Person.prototype);
    + Here our friend create() comes to the rescue again. In this case we are using it to create a new object and make it the value of Teacher.prototype. The new object has Person.prototype as its prototype and will therefore inherit, if and when needed, all the methods available on Person.prototype.
  2. +
  3. We need to do one more thing before we move on. After adding the last line, Teacher.prototype's constructor property is now equal to Person(), because we just set Teacher.prototype to reference an object that inherits its properties from Person.prototype! Try saving your code, loading the page in a browser, and entering Teacher.prototype.constructor into the console to verify.
  4. +
  5. This can become a problem, so we need to set this right. You can do so by going back to your source code and adding the following line at the bottom: +
    Object.defineProperty(Teacher.prototype, 'constructor', {
    +    value: Teacher,
    +    enumerable: false, // so that it does not appear in 'for in' loop
    +    writable: true });
    +
  6. +
  7. Now if you save and refresh, entering Teacher.prototype.constructor should return Teacher(), as desired, plus we are now inheriting from Person()!
  8. +
+ +

Giving Teacher() a new greeting() function

+ +

To finish off our code, we need to define a new greeting() function on the Teacher() constructor.

+ +

The easiest way to do this is to define it on Teacher()'s prototype — add the following at the bottom of your code:

+ +
Teacher.prototype.greeting = function() {
+  let prefix;
+
+  if (this.gender === 'male' || this.gender === 'Male' || this.gender === 'm' || this.gender === 'M') {
+    prefix = 'Mr.';
+  } else if (this.gender === 'female' || this.gender === 'Female' || this.gender === 'f' || this.gender === 'F') {
+    prefix = 'Ms.';
+  } else {
+    prefix = 'Mx.';
+  }
+
+  alert('Hello. My name is ' + prefix + ' ' + this.name.last + ', and I teach ' + this.subject + '.');
+};
+ +

This alerts the teacher's greeting, which also uses an appropriate name prefix for their gender, worked out using a conditional statement.

+ +

Trying the example out

+ +

Now that you've entered all the code, try creating an object instance from Teacher() by putting the following at the bottom of your JavaScript (or something similar of your choosing):

+ +
let teacher1 = new Teacher('Dave', 'Griffiths', 31, 'male', ['football', 'cookery'], 'mathematics');
+ +

Now save and refresh, and try accessing the properties and methods of your new teacher1 object, for example:

+ +
teacher1.name.first;
+teacher1.interests[0];
+teacher1.bio();
+teacher1.subject;
+teacher1.greeting();
+teacher1.farewell();
+ +

These should all work just fine. The queries on lines 1, 2, 3, and 6 access members inherited from the generic Person() constructor (class). The query on line 4 accesses a member that is available only on the more specialized Teacher() constructor (class). The query on line 5 would have accessed a member inherited from Person(), except for the fact that Teacher() has its own member with the same name, so the query accesses that member.

+ +
+

Note: If you have trouble getting this to work, compare your code to our finished version (see it running live also).

+
+ +

The technique we covered here is not the only way to create inheriting classes in JavaScript, but it works OK, and it gives you a good idea about how to implement inheritance in JavaScript.

+ +

You might also be interested in checking out some of the new {{glossary("ECMAScript")}} features that allow us to do inheritance more cleanly in JavaScript (see Classes). We didn't cover those here, as they are not yet supported very widely across browsers. All the other code constructs we discussed in this set of articles are supported as far back as IE9 or earlier, and there are ways to achieve earlier support than that.

+ +

A common way is to use a JavaScript library — most of the popular options have an easy set of functionality available for doing inheritance more easily and quickly. CoffeeScript for example provides class, extends, etc.

+ +

A further exercise

+ +

In our OOP theory section, we also included a Student class as a concept, which inherits all the features of Person, and also has a different greeting() method from Person that is much more informal than the Teacher's greeting. Have a look at what the student's greeting looks like in that section, and try implementing your own Student() constructor that inherits all the features of Person(), and implements the different greeting() function.

+ +
+

Note: If you have trouble getting this to work, have a look at our finished version (see it running live also).

+
+ +

Object member summary

+ +

To summarize, you've got four types of property/method to worry about:

+ +
    +
  1. Those defined inside a constructor function that are given to object instances. These are fairly easy to spot — in your own custom code, they are the members defined inside a constructor using the this.x = x type lines; in built in browser code, they are the members only available to object instances (usually created by calling a constructor using the new keyword, e.g. let myInstance = new myConstructor()).
  2. +
  3. Those defined directly on the constructor themselves, that are available only on the constructor. These are commonly only available on built-in browser objects, and are recognized by being chained directly onto a constructor, not an instance. For example, Object.keys(). These are also known as static properties/methods.
  4. +
  5. Those defined on a constructor's prototype, which are inherited by all instances and inheriting object classes. These include any member defined on a Constructor's prototype property, e.g. myConstructor.prototype.x().
  6. +
  7. Those available on an object instance, which can either be an object created when a constructor is instantiated like we saw above (so for example var teacher1 = new Teacher( name = 'Chris' ); and then teacher1.name), or an object literal (let teacher1 = { name = 'Chris' } and then teacher1.name).
  8. +
+ +

If you are not sure which is which, don't worry about it just yet — you are still learning, and familiarity will come with practice.

+ +

ECMAScript 2015 Classes

+ +

ECMAScript 2015 introduces class syntax to JavaScript as a way to write reusable classes using easier, cleaner syntax, which is more similar to classes in C++ or Java. In this section we'll convert the Person and Teacher examples from prototypal inheritance to classes, to show you how it's done.

+ +
+

Note: This modern way of writing classes is supported in all modern browsers, but it is still worth knowing about the underlying prototypal inheritance in case you work on a project that requires supporting a browser that doesn't support this syntax (most notably Internet Explorer).

+
+ +

Let's look at a rewritten version of the Person example, class-style:

+ +
class Person {
+  constructor(first, last, age, gender, interests) {
+    this.name = {
+      first,
+      last
+    };
+    this.age = age;
+    this.gender = gender;
+    this.interests = interests;
+  }
+
+  greeting() {
+    console.log(`Hi! I'm ${this.name.first}`);
+  };
+
+  farewell() {
+    console.log(`${this.name.first} has left the building. Bye for now!`);
+  };
+}
+
+ +

The class statement indicates that we are creating a new class. Inside this block, we define all the features of the class:

+ + + +

We can now instantiate object instances using the new operator, in just the same way as we did before:

+ +
let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
+han.greeting();
+// Hi! I'm Han
+
+let leia = new Person('Leia', 'Organa', 19, 'female', ['Government']);
+leia.farewell();
+// Leia has left the building. Bye for now
+
+ +
+

Note: Under the hood, your classes are being converted into Prototypal Inheritance models — this is just syntactic sugar. But I'm sure you'll agree that it's easier to write.

+
+ +

Inheritance with class syntax

+ +

Above we created a class to represent a person. They have a series of attributes that are common to all people; in this section we'll create our specialized Teacher class, making it inherit from Person using modern class syntax. This is called creating a subclass or subclassing.

+ +

To create a subclass we use the extends keyword to tell JavaScript the class we want to base our class on,

+ +
class Teacher extends Person {
+  constructor(subject, grade) {
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+ +

but there's a little catch.

+ +

Unlike old-school constructor functions where the new operator does the initialization of this to a newly-allocated object, this isn't automatically initialized for a class defined by the extends keyword, i.e the sub-classes.

+ +

Therefore running the above code will give an error:

+ +
Uncaught ReferenceError: Must call super constructor in derived class before
+accessing 'this' or returning from derived constructor
+ +

For sub-classes, the this intialization to a newly allocated object is always dependant on the parent class constructor, i.e the constructor function of the class from which you're extending.

+ +

Here we are extending the Person class — the Teacher sub-class is an extension of the Person class. So for Teacher, the this initialization is done by the Person constructor.

+ +

To call the parent constructor we have to use the super() operator, like so:

+ +
class Teacher extends Person {
+  constructor(subject, grade) {
+    super(); // Now 'this' is initialized by calling the parent constructor.
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+ +

There is no point having a sub-class if it doesn't inherit properties from the parent class.
+ It is good then, that the super() operator also accepts arguments for the parent constructor.

+ +

Looking back to our Person constructor, we can see it has the following block of code in its constructor method:

+ +
 constructor(first, last, age, gender, interests) {
+   this.name = {
+     first,
+     last
+   };
+   this.age = age;
+   this.gender = gender;
+   this.interests = interests;
+} 
+ +

Since the super() operator is actually the parent class constructor, passing it the necessary arguments of the Parent class constructor will also initialize the parent class properties in our sub-class, thereby inheriting it:

+ +
class Teacher extends Person {
+  constructor(first, last, age, gender, interests, subject, grade) {
+    super(first, last, age, gender, interests);
+
+    // subject and grade are specific to Teacher
+    this.subject = subject;
+    this.grade = grade;
+  }
+}
+
+ +

Now when we instantiate Teacher object instances, we can call methods and properties defined on both Teacherand Person as we'd expect:

+ +
let snape = new Teacher('Severus', 'Snape', 58, 'male', ['Potions'], 'Dark arts', 5);
+snape.greeting(); // Hi! I'm Severus.
+snape.farewell(); // Severus has left the building. Bye for now.
+snape.age // 58
+snape.subject; // Dark arts
+
+ +

Like we did with Teachers, we could create other subclasses of Person to make them more specialized without modifying the base class.

+ +
+

Note: You can find this example on GitHub as es2015-class-inheritance.html (see it live also).

+
+ +

Getters and Setters

+ +

There may be times when we want to change the values of an attribute in the classes we create or we don't know what the final value of an attribute will be. Using the Teacher example, we may not know what subject the teacher will teach before we create them, or their subject may change between terms.

+ +

We can handle such situations with getters and setters.

+ +

Let's enhance the Teacher class with getters and setters. The class starts the same as it was the last time we looked at it.

+ +

Getters and setters work in pairs. A getter returns the current value of the variable and its corresponding setter changes the value of the variable to the one it defines.

+ +

The modified Teacher class looks like this:

+ +
class Teacher extends Person {
+  constructor(first, last, age, gender, interests, subject, grade) {
+    super(first, last, age, gender, interests);
+    // subject and grade are specific to Teacher
+    this._subject = subject;
+    this.grade = grade;
+  }
+
+  get subject() {
+    return this._subject;
+  }
+
+  set subject(newSubject) {
+    this._subject = newSubject;
+  }
+}
+
+ +

In our class above we have a getter and setter for the subject property. We use _ to create a separate value in which to store our name property. Without using this convention, we would get errors every time we called get or set. At this point:

+ + + +

The example below shows the two features in action:

+ +
// Check the default value
+console.log(snape.subject) // Returns "Dark arts"
+
+// Change the value
+snape.subject = "Balloon animals" // Sets _subject to "Balloon animals"
+
+// Check it again and see if it matches the new value
+console.log(snape.subject) // Returns "Balloon animals"
+
+ +
+

Note: You can find this example on GitHub as es2015-getters-setters.html (see it live also).

+
+ +
+

Note: Getters and setters can be very useful at times, for example when you want to run some code every time a property is requested or set. For simple cases, however, plain property access without a getter or setter will do just fine.

+
+ +

When would you use inheritance in JavaScript?

+ +

Particularly after this last article, you might be thinking "woo, this is complicated". Well, you are right. Prototypes and inheritance represent some of the most complex aspects of JavaScript, but a lot of JavaScript's power and flexibility comes from its object structure and inheritance, and it is worth understanding how it works.

+ +

In a way, you use inheritance all the time. Whenever you use various features of a Web API , or methods/properties defined on a built-in browser object that you call on your strings, arrays, etc., you are implicitly using inheritance.

+ +

In terms of using inheritance in your own code, you probably won't use it often, especially to begin with, and in small projects. It is a waste of time to use objects and inheritance just for the sake of it when you don't need them. But as your code bases get larger, you are more likely to find a need for it. If you find yourself starting to create a number of objects that have similar features, then creating a generic object type to contain all the shared functionality and inheriting those features in more specialized object types can be convenient and useful.

+ +
+

Note: Because of the way JavaScript works, with the prototype chain, etc., the sharing of functionality between objects is often called delegation. Specialized objects delegate functionality to a generic object type.

+
+ +

When using inheritance, you are advised to not have too many levels of inheritance, and to keep careful track of where you define your methods and properties. It is possible to start writing code that temporarily modifies the prototypes of built-in browser objects, but you should not do this unless you have a really good reason. Too much inheritance can lead to endless confusion, and endless pain when you try to debug such code.

+ +

Ultimately, objects are just another form of code reuse, like functions or loops, with their own specific roles and advantages. If you find yourself creating a bunch of related variables and functions and want to track them all together and package them neatly, an object is a good idea. Objects are also very useful when you want to pass a collection of data from one place to another. Both of these things can be achieved without use of constructors or inheritance. If you only need a single instance of an object, then you are probably better off just using an object literal, and you certainly don't need inheritance.

+ +

Alternatives for extending the prototype chain

+ +

In JavaScript, there are several different ways to extend the prototype of an object aside from what we've shown above. To find out more about the other ways, visit our Inheritance and the prototype chain article.

+ +

Test your skills!

+ +

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Object-oriented JavaScript.

+ +

Summary

+ +

This article has covered the remainder of the core OOJS theory and syntax that we think you should know now. At this point you should understand JavaScript object and OOP basics, prototypes and prototypal inheritance, how to create classes (constructors) and object instances, add features to classes, and create subclasses that inherit from other classes.

+ +

In the next article we'll have a look at how to work with JavaScript Object Notation (JSON), a common data exchange format written using JavaScript objects.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Objects/Object_prototypes", "Learn/JavaScript/Objects/JSON", "Learn/JavaScript/Objects")}}

+ +

In this module

+ + -- cgit v1.2.3-54-g00ecf